C 调用free()会导致程序崩溃
我遇到了一个非常奇怪的问题,试图在分配的内存中调用free会导致我的程序崩溃 以下是相关代码:C 调用free()会导致程序崩溃,c,crash,printf,malloc,free,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*)m
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*/
这是用于新_节点的我的结构:
/*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));
然后通过数组一次(未定义的行为):
您是如何分配
新节点的?@timrau新节点是二元搜索树的一部分,在不同的函数中分配。(*new_node
作为参数传递到我的函数中)您没有包含此声明,但是,如果new_node->name
不是指针,则new_node->name=说明符“代码>将出现问题,因为您将丢失指向以前分配的内存的指针。@pedwards我已添加了我的结构类型。”。您可以看到新节点->名称将是char类型。关键问题是什么是新节点
?为了使用->
,应该将其定义为struct item*new\u节点。如果是这种情况,则必须首先分配struct item
的一个实例,否则将进行涂鸦。请包括您对新节点的定义
。。。不是结构。
specifier[count + 1] = '\0';