Jonathan Martin Jonathan Martin - 11 days ago 5x
C Question

Assignment in condition of if goes wrong

I'm dynamically allocating memory for a struct with this line of code:

if (DrinkMachine = (Drink_Machine*)malloc(sizeof(DrinkMachine) * size) == NULL)

I've also tried:

if (DrinkMachine = (Drink_Machine*)malloc(sizeof(DrinkMachine[size])) == NULL)

Now, due to an error in my code (somewhere), it's failing to dynamically allocate the memory and the pointer is indeed NULL. However, it doesn't return NULL, or otherwise attempt to enter the if statement, even though it should be true. What gives?

Edit: Additional Information. Each item in my struct shows "Unable to read memory" in the watch, when I step through the debugger. Don't know if this helps anyone, but I figured I'd add it to the question.

Edit2: So This was answered I just wanted to make it visible in an edit.

if ((DrinkMachine = (Drink_Machine*)malloc(sizeof(Drink_Machine) * size)) == NULL)
return NULL;

This is the right way to type this. Note, I also edited the code to properly show Drink_Machine in the sizeof(). Not including that was a typo. Others have stated that apparently, it's smarter to just declare the code separately then test the pointer in the next statement. (and one typo corrected)

Thanks to everyone who took the time to answer this question!


You need to wrap the assignment in parenthesis in order to force precedence.

if((DrinkMachine = (Drink_Machine *)malloc(sizeof(DrinkMachine) * size)) == NULL) {
    /* DrinkMachine is NULL */