1) You have a mistake in your printf
format string, you need to actually tell it to print the integer you're passing: %d
or %i
2) You're realloc
ing the same number of bytes with every call, you need to increase it.
3) To be fully standards compliant, use int main(void)
.
4) See here to find out why not to cast the result of malloc
in C.
5) realloc
can accept a NULL
pointer and the result is well-defined, so your initial malloc
call is not needed anyway.
6) Use a named constant + sizeof(type/variable)
to make your code more robust and maintainable (and correct, because sizeof(int)
need not be 4).
All these things combined, here's how I'd rewrite your code:
#include <stdio.h>
#include <stdlib.h>
#define REALLOC_NUM_ELEMENTS 10
int main(void)
{
int *p = NULL;
int m = 0;
while (p = realloc(p, (m + REALLOC_NUM_ELEMENTS * sizeof(int))))
m += REALLOC_NUM_ELEMENTS * sizeof(int);
printf("Number of bytes allocated for heap %d\n", m);
}