4 ms·
Making realloc with a size 0 be undefined is a way of maintaining existing code, because it means that different implementations kan keep doing what they are do
by quelsolaar 3y ago
Making realloc with a size 0 be undefined is a way of maintaining existing code, because it means that different implementations kan keep doing what they are doing. Some implementations free the pointer, some create a zero size allocation. Since there are code depending on both behaviours, we cant define a consistent behaviour, without breaking code that depends on another behaviour. This way we acknowledge the issue without breaking anything.
There was a discussion if it should be defined as "platform defined" instead, but the wg14 wanted to indicate that they discourage this use of realloc, and undefined behaviour was a way of doing this.
- ndiddy 3y agoMaking realloc(buff, 0) undefined means that the compiler is permitted to do nothing instead of calling free on buff. Because this both complies with the C23 standard and makes the computer do less work, I won't be surprised if we start seeing compilers applying this optimization. Hopefully we'll at least get a "-frealloc-size-zero-free" compiler flag or something. BTW, if the "we" implies you're a WG14 member, I wanted to thank you for helping move the language forward. C23 has tons of nice features that makes it compelling to move to (#embed, true/false being keywords, binary literals, built-in endianness macros, etc), which is why I'm concerned about adding more undefined behavior to the standard because some BSD variants didn't comply with the previous standard.
- quelsolaar 3y agoI am in the wg14. But you should not thank me for those features. I'm not very happy with C23. We are working on making UB more understood, and to try to eliminate some UB. To be clear: BSD was not breaking the standard, the standard didn't spell out what the correct action was. So different people had different interpretations. The standard states that things that aren't explicitly defined are UB, so one interpretation is that it was UB to begin with.
- deleted 3y ago[deleted]
- matheusmoreira 3y ago> zero size allocation Is this useful for anything? I wrote my own memory allocator, is there any reason I might want to support this?
- quelsolaar 3y agoIm not recommending doing this, but you may want to allocate an address to use as a magic number. NULL is a magic number address that is guaranteed never to be a valid allocation. By allocating an address, you can creat your own magic number, that wont ever be used by any other allocation so you can give it special meaning in your code.