调用 free() 导致我的程序崩溃
Calling free() causes my program to crash
我遇到了一个非常奇怪的问题,试图在分配的内存块上调用 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] = '[=10=]';
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
个元素分配了 space ...
specifier = (char*) malloc ( (count+1) * sizeof(char));
然后通过你的数组(未定义的行为):
specifier[count + 1] = '[=11=]';
我遇到了一个非常奇怪的问题,试图在分配的内存块上调用 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] = '[=10=]';
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
个元素分配了 space ...
specifier = (char*) malloc ( (count+1) * sizeof(char));
然后通过你的数组(未定义的行为):
specifier[count + 1] = '[=11=]';