![](/img/trans.png)
[英]Why realloc with size '0' allows to free the pointer multiple times but not malloc with size '0'?
[英]free()ing multiple times if malloc() and realloc() was called multiple times in a loop
假设我有一段包含此代码的代码
s = strtok_r(buffer, " \t\n", &saveptr);
do
{
inStr = (char*)malloc(strlen(s)+1);
(void) strncpy(inStr, s, strlen(s)+1);
inputStrings=(char**)realloc(inputStrings,(nElems+1)*sizeof(char*));
inputStrings[nElems] = inStr;
nElems++;
}
while((s = strtok_r(NULL, " \t\n", &saveptr))!=NULL);
我是否需要多次free()inStr和inputStrings(特别是for循环中的inputStrings,最多可达nElems个)或一次? 到目前为止,我还没有找到任何直接解决此问题的文章,因此我认为释放一次就足够了。 如果此问题缺少任何信息,请告知我。 谢谢。
不,如果成功,则对realloc
的调用将释放旧缓冲区。 您只需要做free (inputStrings);
此循环后一次。
但是,在释放它之前,您将需要遍历inputStrings
并对其中的每个条目进行free
调用(这对应于inStr = malloc
...的调用。
您只需要free(inputStrings)
一次free(inputStrings)
。 所有的realloc()
调用都会释放旧块并分配一个新块。
你需要free(inputStrings[i])
的每一个值i
从0
到nElems-1
分配的所有内容最终都需要释放。
完成数组操作后,您应该执行以下操作:
for (i = 0; i < nElems; i++) {
free(inputStrings[i]);
}
free(inputStrings);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.