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;

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);

        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

8 Years
Discussion Span
Last Post by WaltP

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.