繁体   English   中英

调用free()导致我的程序崩溃

[英]Calling free() causes my program to crash

我有一个很奇怪的问题,尝试在分配的内存上免费调用会导致我的程序崩溃。

以下是相关代码:

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';

暂无
暂无

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

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