1.進程記憶體結構
1)代碼區(text segment)。載入的是可執行檔程式碼片段
2)全域初始化資料區/待用資料區(Data Segment)。載入的是可執行檔資料區段,儲存於資料區段的資料的生存周期為整個程式運行過程
3)未初始化資料區(BSS)
4)堆區(heap)用於動態記憶體分配
一般由程式員分配和釋放,若程式員不釋放,程式結束時有可能由OS回收
5)棧區(stack)。由編譯器自動分配釋放,存放函數的參數值、傳回值、局部變數等。
2.malloc/free
malloc函數用來在堆中分配空間
#include <stdlib.h>
void *malloc(size_t size);
其大小由指定的size決定
malloc()函數在記憶體動態儲存裝置區中分配一個長度為size位元組的連續空間,返回一個指向所分配的連續儲存域的起始地址指標
但未能成功分配時(記憶體不足)返回一個NULL指標
void free(void *ptr);//用完後要釋放
-------------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
int count;
int* array;
if((array=(int *)malloc(10*sizeof(int)))==NULL)
{
printf("malloc memory unsuccessful");
exit(1);
}
for (count=0;count<10;count++)
{
*array=count;
array++;
}
for(count=9;count>=0;count--)
{
array--;
printf("%4d",*array);
}
printf("/n");
free(array);
array=NULL;
exit (0);
}
-------------------------------------------------------------------------------------------------------
[root@localhost sys_source]# ./test
9 8 7 6 5 4 3 2 1 0
--------------------------------------------------------------------------------------------------------
3.記憶體管理函數
1)memccpy
#include <string.h>
void *memccpy(void *dest, const void *src, int c, size_t n);
memccpy()用來拷貝src所指的記憶體內容前n個位元組到dest所指的地址上。與memcpy()不同的是, memccpy()會在複製時檢查參數c是否出現, 若是則返回dest中值為c的下一個位元組地址。
傳回值:
返回指向dest中值為c的下一個位元組指標。傳回值為0表示在src所指記憶體前n個位元組中沒有值為c的位元組。
--------------------------------------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
main()
{
char a[]="string[a]";
char b[]="string(b)";
memccpy(a, b,'B',sizeof(b));
printf("memccpy():%s/n", a);
}
------------------------------------------------------------------------------------------------
[root@localhost sys_source]# ./test
memccpy():string(b)
2)memset初始化指定記憶體單元
#include <string.h>
void *memset(void *s, int c, size_t n);
memset()會將參數s所指的記憶體地區前n個位元組以參數c填入, 然後返回指向s的指標。在編寫程式時, 若需要將某一數組作初始化, memset()會相當方便。
傳回值:
返回指向s的指標
-----------------------------------------------------------------
#include <stdio.h>
#include <string.h>
main()
{
char s[30];
memset (s,'A',sizeof(s));
s[30]='/0';
printf("%s/n",s);
}
---------------------------------------------------------------
[root@localhost sys_source]# ./test
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
----------------------------------------------------------------
4.Valgrind記憶體偵查工具