简体   繁体   中英

Does this code cause memory leaks?

Someone here asked a questions about the || operator. He wondered why (j=3) || (i=3) (j=3) || (i=3) did not assign 3 to i. That post is here: Determining the print of C

In my first answer to that question I gave this example for how this "feature" could be used:

ptr = malloc(sizeof(*ptr)) || printf("Error\n");

Yes, I know it should be printed to stderr, but that's not the topic. If I remember it correctly, I was told that this construct could cause memory leaks. I find it hard to believe, so please explain to me.

And is there any special reason to not use this construct? Apart from the obvious "because I can" impression it gives?

If the malloc fails, you won't realize it; instead, you'll treat the return value from printf (the number of characters printed) as a memory address, leading to undefined behavior.

This is worse than a memory leak.

Putting parentheses around the assignment will fix this issue, by always assigning ptr to the result of malloc :

(ptr = malloc(sizeof(*ptr))) || printf("Error\n");

However, you'll still need to make sure to avoid using the pointer if the allocation fails, so it won't save you much code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM