Jav*_*ser -1 c crash malloc free printf
我有一个非常奇怪的问题,试图在分配的内存上调用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*/
Run Code Online (Sandbox Code Playgroud)
这是我用于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;
};
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,第一个printf打印正确,但第二个没有.任何想法为什么?
你为count + 1元素分配空间......
specifier = (char*) malloc ( (count+1) * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
然后去一个你的数组(未定义的行为):
specifier[count + 1] = '\0';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3131 次 |
| 最近记录: |