我有一个非常奇怪的问题,试图在分配的内存上调用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] = ' '; new_node->name = specifier; printf("%sn", new_node->name); free(specifier); /*PROGRAM CRASHES HERE*/ printf("boomn"); 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] = ' ';
以上就是c/c++开发分享调用free()会导致程序崩溃相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/519550.html