//char char **p; declared in .h file
size_t bs = 5;
size_t Size = sizeof(obj);
p = (char**)malloc(bs);
for (size_t i = 0; i < bs;i++){p[i] = (char*)malloc(Size);}
for (size_t j = 0; j < bs-1; j ++){p[j] = &(p[j + 1][0]); }
for (size_t i = 0; i < bs; i++){free(p[i]);}
free(p);
尝试释放 for 循环中 p 的最后一个元素时,我的代码停止运行。任何人我可能做错了什么?
编辑:即使将其更改为 (char* )malloc(bs sizeof(char *));我仍然有同样的问题
这仍然不起作用:
size_t bs = 5;
size_t Size = sizeof(obj);
p = (char**)malloc(bs* sizeof(char *));
for (size_t i = 0; i < bs;i++){p[i] = (char*)malloc(Size);}
for (size_t j = 0; j < bs-1; j ++){p[j] = &(p[j + 1][0]); }
for (size_t i = 0; i < bs; i++){free(p[i]);}
free(p);
使用 new 而不是 malloc 也不能解决问题
但是,此代码可以很好地释放内存。
size_t bs = 5;
size_t Size = sizeof(obj);
p = (char**)malloc(bs* sizeof(char *));
for (size_t i = 0; i < bs;i++){p[i] = (char*)malloc(Size);}
for (size_t i = 0; i < bs; i++){free(p[i]);}
free(p);
所以问题似乎与这段代码有关
for(size_t j = 0; j < bs-1; j ++){p[j] = &(p[j + 1][0]); }
我希望这是一个隐式链表,任何人都知道我做错了什么?