Search code examples
cpointersmallocfreedynamic-memory-allocation

How can malloc take more number of bytes of data than assigned


According to what I have understood about malloc() is it allows us to assign the memory dynamically during the runtime. Below is the code that I am looking into

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main() {
  char *description;
  clrscr();
  description = malloc(2*sizeof(char));
  strcpy(description,"Hello there!");
  printf("%s",description);
  free(description);
  printf("%s",description);
  getch();
}

My question is I am asking system to assign 2 bytes of memory in the malloc() function. So when I try to fill the string "Hello there!" and print the same I should get only the first 2 characters of the string as output but I am getting the whole string that I have given in strcpy() function in the output.

And also after I use free() function if I try to print description again I should not get any output if I am not wrong but I am still getting the same string again. May in know how this works. I am using turbo C++ compiler.


Solution

  • Malloc allocates 2 bytes. This means from a starting point (the one returned by the malloc) give me 2 bytes. strcpy copies all bytes in the string "hello there!" starting at the address in description. This does not care about the allocation, it just copies the bytes. The %s in printf tells printf to look for a null terminated string.

    free() is used to tell the memory manager that the bytes can be used for other purposes again. It does not erase the data already present.

    As @Michael Foukarakis pointed out, writing bytes in unallocated memory may cause undefined behavior. If something else were to write on the not allocated memory between the statements things will break.