如何正确免费字符**用C [英] How to properly free char** in C

查看:96
本文介绍了如何正确免费字符**用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的已经搞不清楚这个二维字符数组

 的char ** ARG =的malloc(sizeof的(字符*)* ARGC)
的for(int i = 0; I< ARGC,我++)
  ARG [I] =的malloc(sizeof的(char)的*尺寸)
...
...

现在假设经过一系列的操作,我忘了变量ARGC,我怎么能释放这些记忆?
我可以做这样的事情?这是在任何情况下绝对正确的?

 的char ** TMP = ARG;
而(* TMP!= NULL){
    免费(* TMP);
    TMP ++;
}
免费(ARG);


解决方案

没有

 而(* TMP!= NULL){

您可能达到上面,你会间接引用的内存还没有被分配到并引发未定义行为的一个点。

或者像建议你可以明确分配 NULL 到最后分配的指针,在这种情况下,它会正常工作。

I have really been confused about this 2D char array

char **arg = malloc(sizeof(char*) * argc)
for (int i = 0; i < argc; i++)
  arg[i] = malloc(sizeof(char) * size)
...
...

Now suppose after a series of operations, I forget the variable argc, how can I free those memory? Can I do something like this? Is this absolutely correct under all circumstances?

char **tmp = arg;
while (*tmp != NULL){
    free(*tmp); 
    tmp++;
}
free(arg);

解决方案

No

while(*tmp != NULL){

you may reach above a point where you will dereference memory which hasn't been assigned to and trigger undefined behaviour.

Or as suggested you can explicitly assign a NULL to the last allocated pointer, and in that case it will work.

这篇关于如何正确免费字符**用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆