Hello,
I have a conceptual code related to the C memory allocation model

if I have some code of this form, I will get a seg fault

int main()
{
     char* p;
     *(p+5)='A';
      printf("%c\n",*(p+5));
}

But when I have some code of this form I do not get a seg fault

int main(int argc, char* argv[])
{
        char* p=(char *)malloc(10);
        *(p+15)='A';
        printf("%c\n",*(p+15));

        return 1;
}

But I am unable to understand the reason for this. In both the case I am writing to unallocated memory. So why am I not getting a seg fault in the 2nd case

Because in the first case, the pointer p is pointing nowhere. You defined the pointer, but never pointed it to space for the data.

In the second, you allocated data space, and the address was placed into the pointer. But the only reason it didn't segfault is luck. The space malloc 'd obviously included some fudge room. It could be that the malloc actually allocates a buffer in chunks by K. Another malloc would take more from that chunk without having to access the heap.

This article has been dead for over six months. Start a new discussion instead.