2
int main()
{
    int *p=NULL;
    p=malloc(8);

    if (p==NULL)
        printf("Mem alloc failed\n");
    else
        printf("Passed\n");

    unsigned long int i=0;

    for (i=2;i<=10000;i++)
        p[i]=10;  // I thought as we are increasing beyond malloc size of 8 bytes there should be segmentation fault but I was wrong.

    printf("p[10000]= %d %d\n",p[10000]);

    free(p);
    return 0;
}

What can be the reason behind this as I tried to increase for loop count to

pow(2,32) ( for(i=2;i<=((pow(2,32)-1));i++))

in which case I get a segmentation fault?

Jamal
  • 763
  • 7
  • 22
  • 32
Nishith Goswami
  • 353
  • 5
  • 13
  • 1
    What do you *expect* to happen ? Always remember that "nothing happening" is one possible outcome of undefined behaviour. – Paul R Sep 11 '13 at 07:18
  • "I thought as we are increasing beyond malloc size of 8 bytes there should be segmentation fault" -- Why did you think that? Do you understand what a segfault is, what causes it, and how malloc and the operating system support it uses work? And why did you stop at 10000? – Jim Balter Sep 11 '13 at 08:59

2 Answers2

2

There is no guarantee a crash will actually happen. This kind of error is often silently ignored. It's even possible to write to the memory used to store internal structures of runtime memory management system, and thus corrupt the heap. It's an undefined behaviour, after all - nothing is guaranteed.

Anyway, preventing heap overflow in general is a subject of extensive research. Apparently, at this moment it's possible, but degrades performance significantly. Try googling for "heap overflow protection" if you find the topic interesting, you'll likely find a wide range of papers and technical descriptions of state-of-the-art techniques and current developements.

Marcin Łoś
  • 3,226
  • 1
  • 19
  • 21
1

what you described here is an undefined behavior, that might cause Exception, might be ignored, and might do just about anything, because the behavior is undefined:

behaviour, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.

Undefined behaviour may also be expected when this International Standard omits the description of any explicit definition of behavior.

Community
  • 1
  • 1
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70