Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does malloc seem to not be creating a new variable?

Tags:

c

malloc

Really dumb question. Here's my sample code:

#include <stdio.h>
#include <stdlib.h>

typedef struct sample {
  int a;
  int b;
} SAMPLE_T;

int main() {
  int i, max = 4;
  for (i = 0; i < max; i++)
  {
     SAMPLE_T * newsamp = (SAMPLE_T *)malloc(sizeof(SAMPLE_T));
     printf("addr: %x\n", &newsamp);
  }
}

I'm trying to 'create' a new variable each time I go through the loop, and I thought that this would do the trick, since malloc would create a new variable on the heap. But, it seems I've messed something up. Here's the output:

addr: bfc29c4
addr: bfc29c4
addr: bfc29c4
addr: bfc29c4

Am I not understanding how malloc is working?

like image 421
Pat Avatar asked Dec 21 '25 05:12

Pat


1 Answers

The address of newsamp is not changing, which is not surprising. Try:

 printf("addr: %x\n", newsamp)

Also, even though this is obviously just a toy program you really should free the memory before the loop terminates.

like image 106
William Pursell Avatar answered Dec 22 '25 19:12

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!