Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c - Freeing non-malloc'd memory

Let's say I declare the following array:

char *arr[3];

During running the program, depending on the user's inputs, I may or may not allocate strings of memory into this array (meaning arr[i]).

Is it safe to free(arr[i]) at the end of the program without checking which of them I allocated? Or could this cause errors?

Thanks!

question from:https://stackoverflow.com/questions/65863527/freeing-non-mallocd-memory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is safe to pass a null pointer to free, so if your array is initialized with null pointers, you can safely free all arr[i], assuming you only store pointers return by malloc() and friends and do not free them elsewhere.

Define the array as

char *arr[3] = { NULL, NULL, NULL };

or simply

char *arr[3] = { 0 };

NULL, 0 and '' may be used to specify a null pointer, but it is advisable to follow a simple rule of clarity:

  • use NULL for a null pointer,
  • use 0 for a null integer,
  • use '' for a null byte in an array of char, which is also called the null terminator.

And you can use = { 0 }; as an initializer for any C object: all elements and members will be intialized to the zero value of their type, except for unions where only the first member is initialized this way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...