3

I'm running into this (short) code and I'm not sure what it exactly does;

int amount = 5
int totalAllocatedMemory = 0;
totalAllocatedMemory += amount, malloc(amount);

It seems that 'malloc' has no effect here!

Thanks

Roronoa Zoro
  • 1,013
  • 2
  • 15
  • 25
  • 8
    Sure it has an effect - it creates a memory leak. – Mark Ransom Jan 25 '12 at 17:57
  • 1
    Not a real question, not constructive, too localized... how to decide?! – tenfour Jan 25 '12 at 18:01
  • The "totalAllocatedMemory" is a different name from "totalAllocatedMemroy" so it may not be doing what you think it's doing. Also, you are missing a semicolon after the first line. In any case, it does leak memory. – Branko Dimitrijevic Jan 25 '12 at 18:07
  • I've seen embedded system malloc "implementations" which allocate linearly and have no (meaningful) free counterpart, so it could be that the `amount` here is moving the malloc linear allocator pointer to an aligned address. I can't think why else it could have been made. – Tom Whittock Jan 25 '12 at 19:01

3 Answers3

3

It does have an effect, in that it allocates memory. However, the code does look bizarre and the memory does get leaked.

In case you're wondering about the syntax and exact semantics, see How does the Comma Operator work

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

It:

  • Allocates 5 byes
  • Adds 5 to totalAllocatedMemroy (typo?)
  • Leaks the memory
Ingemar
  • 1,638
  • 2
  • 12
  • 15
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

Well the code looks buggy but here's what it does:

  • Adds amount to totalAllocatedMemory
  • Allocates 5 bytes and discards the result (which would be the address of the allocated memory, therefore as others said results to a memory leak)

This is because comma has the lowest precedence of all operators in C.

xpapad
  • 4,376
  • 1
  • 24
  • 25