Chinaunix
标题:
如何释放字符串数组的空间
[打印本页]
作者:
104359176
时间:
2018-08-01 09:46
标题:
如何释放字符串数组的空间
字符串数组也是一个数组,不过是指针数组,如果要释放,是先释放里面的字符串空间,还是直接释放这个字符串数组:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char **strs = calloc(4, sizeof(char *));
for (int i = 0, i < 4; i++) {
char *str = calloc(2, sizeof(char));
str[0]= 'a';
}
/*
how to free strs
*/
return 0;
}
复制代码
作者:
lxyscls
时间:
2018-08-01 10:40
所有malloc/calloc,都要有对应的free
作者:
bruceteen
时间:
2018-08-01 12:48
一个 alloc 必然对应一个 free
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char** strs = malloc( 4*sizeof(char*) ); // 没必要calloc
for( size_t i=0; i!=4; ++i )
{
strs[i] = malloc( 2*sizeof(char) );
strs[i][0] = 'a';
strs[i][1] = '\0';
}
for( size_t i=0; i!=4; ++i )
free( strs[i] );
free( strs );
}
复制代码
作者:
104359176
时间:
2018-08-02 10:47
感谢回答。明白了。关于内存回收的问题,实在是一个需要长期学习总结的大问题。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2