What is the output of the following sample C Code

Int *ptr = (int *)malloc(100*(sizeof(int)));
ptr++;
free(ptr);

Questions by chandan1008

Showing Answers 1 - 9 of 9 Answers

Code
  1. int *ptr = (int *)malloc(100*(sizeof(int)));

  2. ptr++;

  3. free(ptr);

  4.  



i think it will allocate 400 bytes...int taken as 4 bytes..gcc compiler..and send base address to pointer ptr...
next ptr is incremented ptr++=ptr+4..points to next location

now free(ptr)...this will free the memory but ptr will still point to the previous memory location..as free return type is void...
so we have to write ptr=0;
to make it clear..
output no may be same if os doesn't use those mem location used by us previously..and may be different ..depends on o.s.
plz correct if wrong

  Was this answer useful?  Yes

First of all, you can clean up that malloc call (see attached code). You shouldn't cast the result of malloc; its unnecessary, and under compilers that use the 1989/1990 standard, it can suppress a diagnostic if you dont have a declaration for malloc in scope.

The result will likely be a runtime error, since pointer value being passed to free is not the same value that was returned from malloc.

Code
  1. int *ptr = malloc(100 * sizeof *ptr);

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions