Chinaunix

标题: 如何释放字符串数组的空间 [打印本页]

作者: 104359176    时间: 2018-08-01 09:46
标题: 如何释放字符串数组的空间
字符串数组也是一个数组,不过是指针数组,如果要释放,是先释放里面的字符串空间,还是直接释放这个字符串数组:

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int main(void) {
  4.     char **strs = calloc(4, sizeof(char *));
  5.     for (int i = 0, i < 4; i++) {
  6.         char *str = calloc(2, sizeof(char));
  7.         str[0]= 'a';
  8.     }
  9.     /*
  10.     how to free strs
  11.     */
  12.     return 0;
  13. }
复制代码



作者: lxyscls    时间: 2018-08-01 10:40
所有malloc/calloc,都要有对应的free
作者: bruceteen    时间: 2018-08-01 12:48
一个 alloc 必然对应一个 free

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int main(void)
  4. {
  5.     char** strs = malloc( 4*sizeof(char*) ); // 没必要calloc
  6.     for( size_t i=0; i!=4; ++i )
  7.     {
  8.         strs[i] = malloc( 2*sizeof(char) );
  9.         strs[i][0] = 'a';
  10.         strs[i][1] = '\0';
  11.     }

  12.     for( size_t i=0; i!=4; ++i )
  13.         free( strs[i] );
  14.     free( strs );
  15. }
复制代码

作者: 104359176    时间: 2018-08-02 10:47
感谢回答。明白了。关于内存回收的问题,实在是一个需要长期学习总结的大问题。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2