2020年4月19日 星期日

C 語言 - malloc、free 與 calloc

malloc 跟 free


    一般來說要將函式結果回傳是不能用 pointer,因為一旦函式結束 stack 的空間就會被釋出,所以 pointer 會指向的資料是危險的。這時就會先動態地宣告一個位址給 pointer,但這類的記憶體會被存放在 heap 而非 stack,所以開發者必須自行釋放。
  • pointer.c
  •     void
        showMalloc(int pointerValue)
        {
            int *p = malloc(sizeof(int));
    
            printf("Address : %p\n", p);
            printf("Value   : %d\n", *p);
    
            *p = pointerValue;
    
            printf("Address : %p\n", p);
            printf("Value   : %d\n", *p);
            
            free(p);
        }
  • output
  •     Address : 00682B90
        Value   : 6826496
        Address : 00682B90
        Value   : 100

calloc


    會幫你初始值的 malloc
  • pointer.c
  •     void
        showMalloc(int pointerValue)
        {
            int *p = calloc(1, sizeof(int));
    
            printf("Address : %p\n", p);
            printf("Value   : %d\n", *p);
    
            *p = pointerValue;
    
            printf("Address : %p\n", p);
            printf("Value   : %d\n", *p);
    
            free(p);
        }
  • output
  •     Address : 00722B90
        Value   : 0
        Address : 00722B90
        Value   : 100

參考資料 :
https://openhome.cc/Gossip/CGossip/MallocFree.html

Related Posts:

  • C 語言 - size_t 及各個常見類型 typedef unsigned int size_t // 通常定義在 stddef.h int8 : -128 ~ 127 int16 : -32768 ~ 32767 int32 : -2147483648 ~ 2147483647 int64 : -9223372036854775808 ~ 9223372036854775807 uint8 : … Read More
  • C 語言 - struct array 初始化 ( Initializing array of structures ) 初始化 struct array struct student { char* name; int grade; int id; }; 1. 依照當初宣告的順序 struct student myStudents[] = { {"Henry", 3, 1}, {"Marry", 3, 2} }; 1. 依照當初宣告的名子 … Read More
  • C 語言 - #ifndef #ifndef 用途 在 .h 檔確保只會被編譯一次 #ifndef HELLO_H // 有些人會定義成 _HELLO_H_ #define HELLO_H // 但目的就是不會被重複編譯 #include <stdlib.h> int helloIntro(char** str); int main() __attribute__((weak)); #endif … Read More
  • C 語言 - warning: left shift count >= width of type warning: left shift count >= width of type     一般來說,就是 shift 的 bit 大於資料型態的 bit 數。但有時使用 unsigned long 仍然會出錯,因為 unsigned long 會依照系統的不同,有時是 32 bit 有時是 64 bit,所以這時用 unsigned long long 較為安全 ( 保證 64 bit… Read More
  • C 語言 - CLI ( Command Line Interface ) 設計 (1)CLI 命令列介面     在設計 CLI 的程式時,最好的方法是遵從 IEEE Std 1003 ( POSIX ) 對 program 的 command-line options 之規範。所以用 getopt 去做 parse command-line 是最簡單的,有一點要注意的是 GNU 提供的 getopt 支援 " -- ",這個 PO… Read More

0 意見:

張貼留言

Popular Posts