DEV Community

Discussion on: I'm an Expert in Memory Management & Segfaults, Ask Me Anything!

Collapse
 
stolaine profile image
Stolaine

How to create segmentation fault using malloc?

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Segmentation faults are just a possible outcome of undefined behavior, which is unpredictable by nature. They are not like exceptions! There is no official or reliable way to "throw" a segmentation fault, as it only occurs with undefined behavior, wherein "it is legal for the compiler to make demons fly out of your nose". No matter how you "cause" a segmentation fault, there's always a chance it will do something else, or even somehow appear to produce valid code instead!

Meanwhile, malloc doesn't tend to have undefined behavior, unless you're dealing with heap corruption (a very bad thing), wherein you somehow wrote into unallocated memory. If that's the case, your problem isn't the malloc call, but rather something elsewhere. Barring problems from elsewhere in the code, malloc will only do one of two things: return a pointer to allocated space, or return a null pointer because it couldn't allocate. Simple as that. :)