user-0 提问: c语言中如何释放子函数中开辟的内存呢？

回复:
user: user-1
content: 子函数realloc完了将指针的地址返回给主函数被，用指针的指针来传递。

user: user-0
content: 引用 19 楼 zhao4zhong1 的回复:楼主功力还不够深厚啊！ 仅供参考： #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <time.h> int K,n; unsigned long ulrand(void) {     return (      (((unsigned long)rand()<<24)&0xFF000000ul)     |(((unsigned long)rand()<<12)&0x00FFF000ul)     |(((unsigned long)rand()    )&0x00000FFFul)); } float **sub(float **p) {     float **p1;     int K1,i,j;      for (i=0;i<K;i++) for (j=0;j<n;j++) p[i][j]=(float)(i*n+j);      while (1) {         K1=ulrand()%100000;         if (K1!=K) break;     }      if (K1<K) {         for (i=K1;i<K;i++) free(p[i]);         p1=(float**)realloc(p,K1*sizeof(float*));         assert(p1);         p=p1;     } else {//K1>K         p1=(float**)realloc(p,K1*sizeof(float*));         assert(p1);         p=p1;         for (i=K;i<K1;i++) {             p[i]=(float*)calloc(n,sizeof(float));             assert(p[i]);         }     }      K=K1;      for (i=0;i<K;i++) for (j=0;j<n;j++) p[i][j]=(float)(i*n+j);      return p; } int main() {     float **P;     int i;      K=ulrand()%100000;     n=ulrand()%1000;      P=(float**)calloc(K,sizeof(float*));     assert(P);     for (i=0;i<K;i++) {         P[i]=(float*)calloc(n,sizeof(float));         assert(P[i]);     }      P=sub(P);      for (i=0;i<K;i++) {         free(P[i]);     }     free(P);      return 0; }  多谢指教！！

user: user-2
content: 楼主功力还不够深厚啊！ 仅供参考： #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <time.h> int K,n; unsigned long ulrand(void) {     return (      (((unsigned long)rand()<<24)&0xFF000000ul)     |(((unsigned long)rand()<<12)&0x00FFF000ul)     |(((unsigned long)rand()    )&0x00000FFFul)); } float **sub(float **p) {     float **p1;     int K1,i,j;      for (i=0;i<K;i++) for (j=0;j<n;j++) p[i][j]=(float)(i*n+j);      while (1) {         K1=ulrand()%100000;         if (K1!=K) break;     }      if (K1<K) {         for (i=K1;i<K;i++) free(p[i]);         p1=(float**)realloc(p,K1*sizeof(float*));         assert(p1);         p=p1;     } else {//K1>K         p1=(float**)realloc(p,K1*sizeof(float*));         assert(p1);         p=p1;         for (i=K;i<K1;i++) {             p[i]=(float*)calloc(n,sizeof(float));             assert(p[i]);         }     }      K=K1;      for (i=0;i<K;i++) for (j=0;j<n;j++) p[i][j]=(float)(i*n+j);      return p; } int main() {     float **P;     int i;      K=ulrand()%100000;     n=ulrand()%1000;      P=(float**)calloc(K,sizeof(float*));     assert(P);     for (i=0;i<K;i++) {         P[i]=(float*)calloc(n,sizeof(float));         assert(P[i]);     }      P=sub(P);      for (i=0;i<K;i++) {         free(P[i]);     }     free(P);      return 0; }

user: user-0
content: 引用 14 楼 shuhaitao333 的回复:[quote=引用 11 楼 user-4 的回复:] [quote=引用 10 楼 shuhaitao333 的回复:] [quote=引用 8 楼 user-4 的回复:] 你的代码是不是  main { char* p = malloc func(p) free(p) }  func(int* p) { p  = realloc }  对吗 对，不过指针都是二级的。[/quote]C语言 只有值传递 你这样做 无法修改main中 p指针的值  p还是指向原来的malloc 得到的内存块  而这个内存块可能在realloc的时候 被释放了  free(已经释放的内存) 就会死  改正可以是 main { int** p = malloc p = func(p) free(p) }  int** func(int* p) { int** pp  = realloc 处理pp return pp; }  另外 以后这样的问题需要把代码也贴出来  查错比较方便   如果代码太长可以和我现在做的一样 做一些精简 保留需要注意的地方[/quote] 看起来是我在楼下说的意思。对不对？[/quote]多谢你，我试试行不行。

user: user-0
content: 引用 16 楼 schlafenhamster 的回复:P1=malloc(m+1行)；//  这是 p 不够大 ；所以 分配 大点的 把p和增加的一行赋给P1；//  把 p 里的 内容 复制到 P1 for（i=0;i<m;i++）//  释放 p 所占的 内存 free (p[i]);// free(p);// 然后   *p=P1；// 主函数 caller 只知道 有 P1。如果 P1 以后不用了， 则在 主 函数 中 释放 它。 好，我试试，多谢。

user: user-3
content: P1=malloc(m+1行)；//  这是 p 不够大 ；所以 分配 大点的 把p和增加的一行赋给P1；//  把 p 里的 内容 复制到 P1 for（i=0;i<m;i++）//  释放 p 所占的 内存 free (p[i]);// free(p);// 然后   *p=P1；// 主函数 caller 只知道 有 P1。如果 P1 以后不用了， 则在 主 函数 中 释放 它。

user: user-0
content: 引用 13 楼 schlafenhamster 的回复:"在主函数中没有释放语句"  主函数 只释放 最后的 p。 void 子函数（int **p） { P1=malloc(m+1行)； 把p和增加的一行赋给P1； for（i=0;i<m;i++）//以下三行要删除？？？？ free (p[i]);// free(p);// 然后 *p=P1； }

user: user-0
content: 引用 11 楼 user-4 的回复:[quote=引用 10 楼 shuhaitao333 的回复:] [quote=引用 8 楼 user-4 的回复:] 你的代码是不是  main { char* p = malloc func(p) free(p) }  func(int* p) { p  = realloc }  对吗 对，不过指针都是二级的。[/quote]C语言 只有值传递 你这样做 无法修改main中 p指针的值  p还是指向原来的malloc 得到的内存块  而这个内存块可能在realloc的时候 被释放了  free(已经释放的内存) 就会死  改正可以是 main { int** p = malloc p = func(p) free(p) }  int** func(int* p) { int** pp  = realloc 处理pp return pp; }  另外 以后这样的问题需要把代码也贴出来  查错比较方便   如果代码太长可以和我现在做的一样 做一些精简 保留需要注意的地方[/quote] 看起来是我在楼下说的意思。对不对？

user: user-3
content: "在主函数中没有释放语句"  主函数 只释放 最后的 p。

user: user-0
content: 引用 9 楼 schlafenhamster 的回复:主函数中开辟 P  -》 给 子程序 -》子程序 发现 P 不够大 ， 开辟 P1， 删除 P ， 返回 P1。  注意这里  P1 是 通过 P 返回的 ， 所以 这个 P 是 2级 指针  即：  void 子函数（int **p） { ；；；； *p=P1； } 你的意思是不是： void 子函数（int **p） { P1=malloc(m+1行)； 把p和增加的一行赋给P1； for（i=0;i<m;i++） free (p[i]); free(p); 然后 *p=P1； } 在主函数中没有释放语句。 我理解的对不对？

user: user-4
content: 引用 10 楼 shuhaitao333 的回复:[quote=引用 8 楼 user-4 的回复:] 你的代码是不是  main { char* p = malloc func(p) free(p) }  func(int* p) { p  = realloc }  对吗 对，不过指针都是二级的。[/quote]C语言 只有值传递 你这样做 无法修改main中 p指针的值  p还是指向原来的malloc 得到的内存块  而这个内存块可能在realloc的时候 被释放了  free(已经释放的内存) 就会死  改正可以是 main { int** p = malloc p = func(p) free(p) }  int** func(int* p) { int** pp  = realloc 处理pp return pp; }  另外 以后这样的问题需要把代码也贴出来  查错比较方便   如果代码太长可以和我现在做的一样 做一些精简 保留需要注意的地方

user: user-0
content: 引用 8 楼 user-4 的回复:你的代码是不是  main { char* p = malloc func(p) free(p) }  func(int* p) { p  = realloc }  对吗 对，不过指针都是二级的。

user: user-3
content: 主函数中开辟 P  -》 给 子程序 -》子程序 发现 P 不够大 ， 开辟 P1， 删除 P ， 返回 P1。  注意这里  P1 是 通过 P 返回的 ， 所以 这个 P 是 2级 指针  即：  void 子函数（int **p） { ；；；； *p=P1； }

user: user-4
content: 你的代码是不是  main { char* p = malloc func(p) free(p) }  func(int* p) { p  = realloc }  对吗

user: user-0
content: 引用 6 楼 schlafenhamster 的回复:子函数中： P=(float**)realloc(P,(m+1)*sizeof(float*)); 等等一系列操作后返回指针P。  返回 P 前， 原来 P 要 删除。  就是 P1=新内存，（比原来大）  复制 P到 P1 删除  P 返回 P1 我推测你的意思是：先在子函数中开辟一个更大的内存P1然后把P放进P1，然后在子函数中删除P，再把P1返回到主函数中。 但是有几个问题：a. P是我在主函数中开辟的，如果我在子函数中释放，可行吗？ b. 怎么样返回P1，这个我不懂具体命令。c. P1是否需要在子函数中释放？还是在主函数中释放？

user: user-3
content: 子函数中： P=(float**)realloc(P,(m+1)*sizeof(float*)); 等等一系列操作后返回指针P。  返回 P 前， 原来 P 要 删除。  就是 P1=新内存，（比原来大）  复制 P到 P1 删除  P 返回 P1

user: user-0
content: 引用 4 楼 schlafenhamster 的回复:不如 分配一个 超大的 内存我也考虑过这么做，毕竟频繁的开辟释放内存也是效率不高的。但是如果分配大内存的话会在其他方面引起麻烦，也会大大降低效率。我要做一个逼近的算法，这样会增加我扫描的范围。

user: user-3
content: 不如 分配一个 超大的 内存

user: user-0
content: 引用 2 楼 zhao4zhong1 的回复:都free了，还怎么realloc？  realloc Reallocate memory blocks.  void *realloc( void *memblock, size_t size );  Routine Required Header Compatibility  realloc <stdlib.h> and <malloc.h> ANSI, Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.  Parameters  memblock  Pointer to previously allocated memory block  size  New size in bytes  Remarks  The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc.  The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes, although the new block can be in a different location. Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument.  realloc calls malloc in order to use the C++ _set_new_mode function to set the new handler mode. The new handler mode indicates whether, on failure, malloc is to call the new handler routine as set by _set_new_handler. By default, malloc does not call the new handler routine on failure to allocate memory. You can override this default behavior so that, when realloc fails to allocate memory, malloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call   _set_new_mode(1)  early in your program, or link with NEWMODE.OBJ.  When the application is linked with a debug version of the C run-time libraries, realloc resolves to _realloc_dbg. For more information about how the heap is managed during the debugging process, see Using C Run-Time Library Debugging Support.  Example  /* REALLOC.C: This program allocates a block of memory for  * buffer and then uses _msize to display the size of that  * block. Next, it uses realloc to expand the amount of  * memory used by buffer and then calls _msize again to  * display the new amount of memory allocated to buffer.  */  #include <stdio.h> #include <malloc.h> #include <stdlib.h>  void main( void ) {    long *buffer;    size_t size;     if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )       exit( 1 );     size = _msize( buffer );    printf( "Size of block after malloc of 1000 longs: %u\n", size );     /* Reallocate and show new size: */    if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))          ==  NULL )       exit( 1 );    size = _msize( buffer );    printf( "Size of block after realloc of 1000 more longs: %u\n",              size );     free( buffer );    exit( 0 ); }   Output  Size of block after malloc of 1000 longs: 4000 Size of block after realloc of 1000 more longs: 8000   Memory Allocation Routines  See Also   calloc, free, malloc  你可能没看清，我realloc是在子函数中使用的。我在主函数中调用子函数以后，在程序的最后才free的。 也就是说我先在主函数中molloc，然后调用子函数realloc，最后才free。

user: user-2
content: 都free了，还怎么realloc？  realloc Reallocate memory blocks.  void *realloc( void *memblock, size_t size );  Routine Required Header Compatibility  realloc <stdlib.h> and <malloc.h> ANSI, Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.  Parameters  memblock  Pointer to previously allocated memory block  size  New size in bytes  Remarks  The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc.  The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes, although the new block can be in a different location. Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument.  realloc calls malloc in order to use the C++ _set_new_mode function to set the new handler mode. The new handler mode indicates whether, on failure, malloc is to call the new handler routine as set by _set_new_handler. By default, malloc does not call the new handler routine on failure to allocate memory. You can override this default behavior so that, when realloc fails to allocate memory, malloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call   _set_new_mode(1)  early in your program, or link with NEWMODE.OBJ.  When the application is linked with a debug version of the C run-time libraries, realloc resolves to _realloc_dbg. For more information about how the heap is managed during the debugging process, see Using C Run-Time Library Debugging Support.  Example  /* REALLOC.C: This program allocates a block of memory for  * buffer and then uses _msize to display the size of that  * block. Next, it uses realloc to expand the amount of  * memory used by buffer and then calls _msize again to  * display the new amount of memory allocated to buffer.  */  #include <stdio.h> #include <malloc.h> #include <stdlib.h>  void main( void ) {    long *buffer;    size_t size;     if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )       exit( 1 );     size = _msize( buffer );    printf( "Size of block after malloc of 1000 longs: %u\n", size );     /* Reallocate and show new size: */    if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))          ==  NULL )       exit( 1 );    size = _msize( buffer );    printf( "Size of block after realloc of 1000 more longs: %u\n",              size );     free( buffer );    exit( 0 ); }   Output  Size of block after malloc of 1000 longs: 4000 Size of block after realloc of 1000 more longs: 8000   Memory Allocation Routines  See Also   calloc, free, malloc