您的位置:首页 > 编程语言 > C语言/C++

C语言,内存管理

2015-10-21 22:42 489 查看

C语言 malloc realloc calloc alloca and free

C语言常用的申请内存函数,malloc,realloc, calloc和 alloca区别

1 申请堆上的内存,使用malloc,realloc,calloc ,需要手动释放。

malloc(size_t size ) 申请size字节的内存,返回指针,内存没有初始化。如果size, 返回为空指针。

calloc(size_t nmemb, size_t size ) 内存的动态存储区中分配nmemb个长度为size的连续空间,函数返回一个指向分配起始地址的指针;如果分配不成功,返回NULL。内存被初始化为零。

realloc( void *ptr, size_t size ) 改变原先指向ptr内存为size字节,不改变原来内存的内容。如果新申请的大小,大于原来的大小,内存不会被初始化。如果ptr为NULL,相当于malloc。

free 释放malloc,calloc和realloc申请的内存大小。

2 申请栈上内存, 使用alloca ,不需要手动释放,自动随着函数退出而释放。

alloca( size_t size ) 从栈上申请size字节的内存。主要,函数栈的大小,不能太大。

在x86-32,使用gcc, 申请1024×1024×32(32M)字节,出现段错误

3 释放动态申请的内存,使用free函数

注意 free 会出现double free 错误,和内存泄漏

例如

char *a, *c, *b;
c = malloc( 1024 );
a = c;
free ( c );


==2842== Memcheck, a memory error detector

==2842== Copyright (C) 2002-2013, and GNU GPL’d, by Julian Seward et al.

==2842== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info

==2842== Command: ./a.out

==2842==

==2842==

==2842== HEAP SUMMARY:

==2842== in use at exit: 0 bytes in 0 blocks

==2842== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated

==2842==

==2842== All heap blocks were freed – no leaks are possible

==2842==

==2842== For counts of detected and suppressed errors, rerun with: -v

==2842== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

char *a, *c, *b;
c = malloc( 1024 );
a = c;
free ( a );
printf( "%p %p", a, c );


==2853== Memcheck, a memory error detector

==2853== Copyright (C) 2002-2013, and GNU GPL’d, by Julian Seward et al.

==2853== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info

==2853== Command: ./a.out

==2853==

==2853==

==2853== HEAP SUMMARY:

==2853== in use at exit: 0 bytes in 0 blocks

==2853== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated

==2853==

==2853== All heap blocks were freed – no leaks are possible

==2853==

==2853== For counts of detected and suppressed errors, rerun with: -v

==2853== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

这里,指针a, b 都是指向同一个内存地址,使用free( a ) 或者free (b ) 都是释放统一内存空间。使用valgrind检测

char *a, *c, *b;
c = malloc( 1024 );
a = c;
free ( a );
free ( c );


出现double free 问题。

主要发生在指针复制时出现,可以采用赋值时,将前个指针,赋值为NULL;

char *a, *c, *b;
c = malloc( 1024 );
a = c;
c = NULL;
free ( a );
free ( c );


注意:realloc函数

p = realloc( p, size ) 当返回是空指针时,原来的指针会被覆盖掉, 出现内存泄漏。

np = realloc( p, szie ) 还可以保留原来的指针,是使用free,释放掉。

char *p;
p = realloc( p, 1024 );
char *newptr = realloc( p, 1024 )


推荐书籍《深入理解计算机系统》(第二版),了解C语言,内存模型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言