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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With