-2
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

main()
{
    int *ptr,i;
    ptr=(int*)malloc(sizeof(int));
    printf("sizo of ptr is:%d",sizeof(ptr));

    for(i=0;i<30;i++)
        scanf("%d",ptr+i);

    for(i=0;i<30;i++)
        printf("%d",*(ptr+i));

    getch();
}

here size of ptr is:4 my question is, i suppose to be store only one integer in ptr but here in this program i could store more than 30 or 100 etc, why it is not throwing an error?

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
user3614789
  • 190
  • 1
  • 11
  • 9
    Because you're having some luck today. It might crash tomorrow. – jweyrich Sep 04 '14 at 13:31
  • i have checked this program in linux and windows. both are giving same result. currently i am using dev c++. – user3614789 Sep 04 '14 at 13:34
  • Related question, about overflowing a buffer on the stack (same general answer): http://stackoverflow.com/questions/23226217/why-buffer-overflow-doesnt-affect-to-this-code – Pascal Cuoq Sep 04 '14 at 13:45

1 Answers1

5

Malloc allocates heap space in chunks of your system page size (typically, 4096 bytes), but it only reserved for your use exactly as much as you requested. If you write beyond your malloced memory, then you risk corrupting your heap or crashing your program with a segmentation violation.

Only as much memory as you requested is guaranteed to be actually yours to use. The block of memory behind the one you requested may be valid, but in use by something else (e.g. stdio library buffers) or reserved for future use (e.g. the next malloc you call).

Sergey L.
  • 21,822
  • 5
  • 49
  • 75