调用free()会导致我的程序崩溃 [英] Calling free() causes my program to crash
本文介绍了调用free()会导致我的程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在那里试图拨打免费分配的内存块会导致我的程序崩溃一个非常奇怪的问题。
I'm having a really weird issue where trying to call free on an allocated piece of memory causes my program to crash.
下面是有关的code:
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*/
这是我的结构是用于new_node:
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;
};
当我运行程序,正确的第一个printf打印,但第二个没有。任何想法,为什么?
When I run the program, that first printf prints correctly, but the second doesn't. Any ideas as to why?
推荐答案
您分配给空格数+ 1
元素...
specifier = (char*) malloc ( (count+1) * sizeof(char));
然后走一过去你的数组(未定义行为):
And then go one past your array (undefined behavior):
specifier[count + 1] = '\0';
这篇关于调用free()会导致我的程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文