Hi Jens and others
thanks for the answer
it does use malloc return value
void *data = malloc(need_size);
if(data == NULL) {//it’s usage of data, is it not????
return 1
} else {
free data;
return 0;
}
checking data for NULL is clearly usage of variable data and compiler can’t
know what outcome of the actual malloc call at runtime
I agree it’s “stupid” code, C/C++ standard doesn’t define code stupidity
code could be valid or not vaild
that code is valid, no doubt
ideally optimization MUST NOT change the code outcome in any way
in the very simple code (I provided) optimization clearly changes code outcome,
which is not acceptable.
suppose I’m writing naive attempt to identify available memory and program exit
with code 1 if memory wasn’t allocated and 0 if memory was allocated
successfully
if malloc is optimized out then my tool won’t work properly, therefore compiler
alters behavior of my program, whatever explanation one can provide
that is not acceptable (g++ and VS work correctly)
> On Jul 4, 2016, at 3:34 PM, Jens Alfke <[email protected]> wrote:
>
>
>> On Jul 4, 2016, at 11:09 AM, Dmitry Markman <[email protected]
>> <mailto:[email protected]>> wrote:
>>
>> clang can’t optimize malloc here, because result of the malloc is used.
>
> It’s only used by free(), whose behavior is also known to the compiler, not
> by anything in your code. Thus the compiler saw that the malloc and free
> together formed a no-op, and optimized them both away.
>
>> also if I use
>> std::cout << "data != NULL" << data << std::endl;
>> malloc wasn’t optimized
>
> Right, because then the program actually uses the pointer, so the compiler
> can’t optimize it away.
>
>> we have much more complex use case where
>> malloc was optimized out,
>
> Did this code actually use the pointer returned by malloc? If so, that would
> seem to be a bug. But the example you showed here isn’t.
>
>
>
>> On Jul 4, 2016, at 11:55 AM, Quincey Morris
>> <[email protected]
>> <mailto:[email protected]>> wrote:
>>
>> I don’t know the answer, but it seems to me at least possible that it didn’t
>> fail. It’s at least possible that it gave you an unmapped virtual allocation
>> of the size you asked for.
>
> No, it does fail — I just tried it on OS X 10.11.5, and with no optimizations
> (-O0) the malloc call isn’t optimized away, and logs:
>
> a.out(9897,0x7fff75a05000) malloc: *** mach_vm_map(size=281474976710656)
> failed (error code=3)
> *** error: can't allocate region
> *** set a breakpoint in malloc_error_break to debug
>
> —Jens
Dmitry Markman
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/xcode-users/archive%40mail-archive.com
This email sent to [email protected]