Search code examples
cmallocheap-memoryfree

Weird behavior of malloc()


Trying to understand answers to my question

what happens when tried to free memory allocated by heap manager, which allocates more than asked for?

I wrote this function and puzzled by its output

int main(int argc,char **argv){
  char *p,*q;
  p=malloc(1); 
  strcpy(p,"01234556789abcdefghijklmnopqrstuvwxyz"); //since malloc allocates atleast 1 byte
  q=malloc(2);
  //    free(q);
  printf("q=%s\n",q);
  printf("p=%s\n",p);

  return 0;
}

Output

q=vwxyz
p=01234556789abcdefghijklm!

Can any one explain this behavior? or is this implementation specific?

also if free(q) is uncommented, I am getting SIGABRT.


Solution

  • You are copying more bytes to *p than you have allocated, overwriting whatever might have been at the memory locations after the allocated space.

    When you then call malloc again, it takes a part of memory it knows to be unused at the moment (which happens to be a few bytes after *p this time), writes some bookkeeping information there and returns a new pointer to that location.

    The bookkeeping information malloc writes happens to start with a '!' in this run, followed by a zero byte, so your first string is truncated. The new pointer happens point to the end of the memory you overwrote before.

    All this is implementation specific and might lead to different results each run or depending on the phase of the moon. The second call to malloc() would also absolutely be in its right to just crash the program in horrible ways (especially since you might be overwriting memory that malloc uses internally).