问题
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