简体   繁体   English

将free()与结构指针一起使用会使程序崩溃

[英]using free() with a struct pointer makes program crash

Error: 错误:

*** Error in `./main': free(): invalid next size (fast): 0x080e1008 ***
Aborted

This is my program, and it's crashing when I try to deallocate a struct. 这是我的程序,当我尝试取消分配结构时会崩溃。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
//struct words contains a word as well as a boolean
//to check if it was used yet or not.
struct words
{
    char * word;
    int bool;
};
//the main function in which everything happens.
//the controller, if you will.
int main()
{
    struct words * word_library = malloc(9);
    struct timeval start, end;
    free(word_library);
    return 0;
}

So this is the code making my program crash: 这是使我的程序崩溃的代码:

free(word_library); 自由(word_library);

What is causing it to crash? 是什么导致它崩溃? And how can prevent this in the future? 以及将来如何防止这种情况发生? I know that every use of malloc() requires the free() after to deallocate it. 我知道,每次使用malloc()都需要在释放它之后使用free()。 But when I don't use free() it ends just fine, but I'm sure there's a memory leak. 但是,当我不使用free()时,它就可以了,但是我确定会发生内存泄漏。

This: 这个:

struct words * word_library = malloc(9);

doesn't allocate space for an array of struct words of size 9. Instead, it allocates 9 bytes. 不会为大小为9的struct words组分配空间,而是分配9个字节。 You need 你需要

struct words * word_library = malloc(sizeof(struct words)*9);

to allocate an array of size 9. 分配大小为9的数组。

You also don't need to allocate and deallocate memory for word in the struct if you are going to make them point to string literals. 如果您要使struct word指向字符串文字,则也不需要为word分配和取消分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM