Calling free() causes my program to crash

主宰稳场 提交于 2019-12-25 18:45:35

问题


I'm having a really weird issue where trying to call free on an allocated piece of memory causes my program to crash.

Here's the relevant code:

int i, count;
char *specifier;
char aisle[1];
count = 0;

/*Find name of the new item and assign to the name field of new_node...*/
for (i = 0; input[i] != ','; i++){
    count++;
}
specifier = (char*)malloc((count+1)*sizeof(char));
if (specifier == NULL){
    printf("Out of memory. Shutting down.\n");
    exit(EXIT_FAILURE);
}
for (i = 0; input[i] != ','; i++){
    specifier[i] = input[i];
}
specifier[count+1] = '\0';
new_node->name = specifier;
printf("%s\n", new_node->name);
free(specifier); /*PROGRAM CRASHES HERE*/
printf("boom\n");
specifier = NULL;
/*Function continues here*/

this is my structure that is used for new_node:

/*Outline for the stock levels system...*/
typedef struct item item_t;
struct item{
    char *name;
    char *aisle;
    item_t *left;
    item_t *right;
 };

When I run the program, that first printf prints correctly, but the second doesn't. Any ideas as to why?


回答1:


You allocate space for count + 1 elements ...

specifier = (char*) malloc ( (count+1) * sizeof(char));

And then go one past your array (undefined behavior):

specifier[count + 1] = '\0';


来源:https://stackoverflow.com/questions/30191242/calling-free-causes-my-program-to-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!