Try   HackMD

[我所不知道的C語言] Null

tags: C C++

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
標題取自於靈感取自於線上講座 - 你所不知道的 C 語言

Null and free/delete

在有GC語言特性的程式語言中,如: C#、Java、Golang,若要清空一個變數的值,會類似這樣寫法:

MyClass name = new MyClass(); name = null;

指派為Null之後,接下來就交給GC去檢查還有沒有去使用這個變數了,但C與C++不一樣,如果動態配置的記憶體,釋放過後只是告訴電腦「我把這個記憶體還給OS了」,而於本處存記憶體位置的變數會是「未定義」的,所以,有一個Best Practice是當釋放記憶體之後,把變數設為null,方便後續要對改變數作處理:

// C int* i = malloc(sizeof(int)); *i = 100; free(i); i = NULL; // C++11 int* i = new int(); *i = 100; delete i; i = nullptr;

還有,在釋放記憶體後,並指派為null的這件事可以避免同一個記憶體重複事後兩次的執行期錯誤:

int* i = malloc(sizeof(int)); free(i); i = NULL; free(i); // No exception in run-time

Reference