Due to concern about the last days / weeks, when I realized that most of my code violates the c99 rules, which leads to undefined behavior, I started to explicitly read the project document ISO / IEC 9899: TC3. In particular, the application “J.2 undefined behavior” Most of them were logical for me, why it is difficult to compose code that violates these rules, or in some cases I might at least think “well, I don’t understand what the problem is with this but I "do so" but there is one point ...
"To access the object (7.20.3), use a non-zero pointer returned by calling the calloc, malloc or realloc function with the requested size zero."
(for anyone who has not read ISO / IEC 9899: TC3 “J.2 undefined behavior”, this section explains what cases will occur in undefined behavior).
So there are so many questions in my head.
First of all:
Why should I allocate a memory block of zero size?
And when I have such a block, what can I do with it?
In order to avoid undefined behavior, maybe I do not want to access memory pointing to it ...
So, I did a bit more research .... looking for several different malloc () pages. and recognized in Linux malloc (3) man:
"If the size is 0, then malloc () returns either NULL or a unique pointer value, which can subsequently be successfully passed to free ()."
Well, the only thing that helped me was: I now have additional questions for you and for me. The case when a function call with identical parameters under the same conditions can return different results is not so difficult to imagine, OK ... but these different results in most cases should not be different. What allows me to suggest a non-zero pointer to the requested zero-sized block may just be an undesirable side effect. does it mean
if ((void *ptr = malloc (0)) == NULL) { }
This is not enough? Do I need to handle * alloc calls like this?
if (X <= 0) { if ((*ptr = malloc (X)) != NULL) { exit (*); } else { } } else { if ((*ptr = malloc (X)) == NULL) { } }
But even if you expect him to get such
"a unique pointer value, which can subsequently be successfully passed to free ()"
how to work with it? I can change it around OK ... I’m even allowed to free it (by the way, that means I have to free it, as I should do with any other allocated memory, or it's just> you are allowed to not disturb your code stream
What is the difference to just make any pointer that way?
void *X = (void *)"1234abc";
I hope that someone can help me in this philosophy of science, or even better than I am interested in it.