Vijay S B Vijay S B - 1 year ago 142
C Question

Dynamic memory allocation in c using malloc

Allocated a

of dynamic memory using
. As I read in some document the immediately below element should be a size of allocated memory using
(In my case it is 200 bytes). But when i executed this below code, got 209 instead 200!

int main()
int *p = (int *)malloc(sizeof(int)*50);

int i;

for(i = 0; i < 5; i++)
scanf("%d", &p[i]);

for(i = -1; i < 5; i++)
printf(" %d ", *((int *)(p+i)));

Can somebody help whats wrong?

Answer Source

This is undefined behavior. You're accessing memory that is outside the region that malloc() returned and this is not valid.

If it was valid in some context, that was an implementation-specific extension and not something you can depend on or do in the general case.

Also, please don't cast the return value of malloc() in C. The printing could just be:

printf(" %d ", p[i]);

the asterisk and cast that you added are not necessary, just use array indexing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download