Writing to pointer out of bounds after malloc() not causing error

It might appear to work fine, but it isn’t very safe at all. By writing data outside the allocated block of memory you are overwriting some data you shouldn’t. This is one of the greatest causes of segfaults and other memory errors, and what you’re observing with it appearing to work in this short program is what makes it so difficult to hunt down the root cause.

Read this article, in particular the part on memory corruption, to begin understanding the problem.

Valgrind is an excellent tool for analysing memory errors such as the one you provide.

@David made a good comment. Compare the results of running your code to running the following code. Note the latter results in a runtime error (with pretty much no useful output!) on ideone.com (click on links), whereas the former succeeds as you experienced.

int main(void)
{
    int *p;
    p=malloc(sizeof(int));
    printf("size of p=%d\n",sizeof(p));
    p[500]=999999;
    printf("p[0]=%d",p[500]);
    p[500000]=42;
    printf("p[0]=%d",p[500000]);
    return 0;
}

Leave a Comment