调用free()会导致程序崩溃
我有一个非常奇怪的问题,试图在分配的内存上调用free导致我的程序崩溃。
这是相关的代码:
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*/
这是我用于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; };
当我运行程序时,第一个printf打印正确,但第二个没有。 任何想法为什么?
你为count + 1
元素分配空间……
specifier = (char*) malloc ( (count+1) * sizeof(char));
然后去一个你的数组(未定义的行为):
specifier[count + 1] = '\0';