(I'll reword the title if anyone has a suggestion, I know it's somewhat awkward.)
When allocating memory for dynamic arrays in C using malloc(), I know to check if the call was successful by verifying that the pointer is not NULL. Does that same check need to be performed for explicitly declared arrays in C, such as in the following example (taken from this question)?
char arrinit[5];
char (*arrinit_two)[5] = &arrinit;
In short: No!
The compiler will assure, that your arrays will have enough memory that you define statically.
Normally (depending, how you declare them), they will be allocated on the stack and when you don't have enough memory on the stack left, your program is likely to crash before you can make any checks or you will not be able to do any remedies.
BTW: You also will not get an NULL value, anyhow, since the system will give you some address value, even when no memory is left (or it has crashed before).
There is of course one case, where you should be careful: When you want to allocate really big amounts of memory (a big array), than you should do it with malloc. On many systems, the stack size is limited for processes, so that it is more likely that your system crashes, when you allocate big amounts of memory on stack (the compiler does it for you) than when you do it with malloc (because there are not the same limits).
But of course on today's computers, this means, that you can have arrays of at least some MB before it has any effect. For arrays < 1MB, you don't need to bother.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With