Richard Heathfield wrote:
ais523 said:
Consider the following program:
#include <stdlib.h>
#include <limits.h>
int main(void)
{
size_t s=SIZE_MAX;
size_t i;
char* p;
while(s--)
{
p=malloc(s);
if(p)
{
i=s;
while(i--) p[i]=42;
free(p);
}
}
return 0;
}
This program would be incredibly slow to run, but I'm interested in
whether or not it causes UB.
It doesn't, as far as I can see.
There seem to be implementations (I
include the operating system as part of the implementation) which would
crash if they tried to run this, due to malloc returning non-NULL when
the system doesn't actually have the memory available (which is
non-conforming behaviour AFAICT).
So: Is this UB, or is it merely a
common implementation non-conformance?
The latter.
As usual, Richard giving both sides of the Möbius fence. ;-)
Michael Wojcik once wrote:
"Oh good, the lazy-allocation religious war has broken out again.
"If no implementation is allowed to fail under the conditions "malloc
returns non-null and later the program tries to use the returned
memory", then no real implementations are not broken. Memory access
can fail for reasons beyond the implementation's control.
"Lazy allocation has its proponents and opponents, and both have
reasonable arguments at their disposal, but this "lazy allocation
breaks conformance" one is not among them. Even if it's true (and no
one has presented a convincing proof of that, IMO), it's pointless,
since many of us have to use implementations on platforms which use
lazy allocation. If those implementations conform except in using
lazy allocation, that will have to be good enough, since there is no
alternative."
--
Peter