调用free()会导致程序崩溃

时间:2015-05-12 12:42:28

标签: c crash printf malloc 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打印正确,但第二个没有。关于为什么的任何想法?

1 个答案:

答案 0 :(得分:5)

您为count + 1元素分配空间......

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

然后跳过你的数组(未定义的行为):

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