Objects of the zero size
2 years, 6 months ago
In what difference between the following pairs of lengths and pointers?
size_t len1 = 0;
char *ptr1 = NULL;
size_t len2 = 0;
char *ptr2 = malloc(0);
size_t len3 = 0;
char *ptr3 = (char *)malloc(4096) + 4096;
size_t len4 = 0;
size_t len5 = 0;
In many cases all five expressions will lead to one result. In others – their behavior can cardinally differ. One of obvious distinctions consists in opportunity to transfer the pointer for its release, but we will not consider it.
The first case interesting, but too strongly differs from others therefore so far we will postpone it.
The behavior of malloc (0) is defined by standards. It is possible to return the null or unique pointer. The second option in many implementations is executed by internal increase in length at unit (which then it is usually rounded to 16). By rules, it is impossible to dereference such pointer, but usually some bytes after all are placed and therefore such program will not fall.
Return of NULL results in possibility of interesting bug. Often return of NULL from malloc is regarded as error.
Read more »