Search code examples
cmallocor-operator

Does this code cause memory leaks?


Someone here asked a questions about the || operator. He wondered why (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?


Solution

  • 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.