Ad

Is Specifying More Size Than Required When Declaring An Array A Bad Practice?

- 1 answer

In C Language, when we don't know the size of the data we're going to hold in the array. Generally, we specify more size than required. Does that not mean we're abusing the memory? Because, the array is stored in sequential manner in the memory, so the processor won't always hold those blocks for the future purpose even if they're not being used currently?

Ad

Answer

In C Language, when we don't know the size of the data we're going to hold in the array. Generally, we specify more size than required.

First of all, We do not need to and do not specify more size than required in general, if we don't know the size at compile time. It might be an impression to you but that's not true.

There are two ways which are used in this case.

Using variable length arrays (VLAs) or dynamic memory allocation.

VLAs are not supported by any C implementation. They were first invented in C99 and are mandatory to implementations compliant to C99 but in implementations compliant to later C standards, VLAs do not need to be supported. So using VLAs makes your code non-portable (if their use is possible).

Also the capability to handling errors is when using VLAs worse. You got no way to check whether the allocation of an VLA was successful or not.

You might better use dynamic memory allocation instead if portability and/or error handling are important points.

Beside that you can resize and free the no longer needed memory if you like to with dynamic memory, which isn't possible with VLAs.


Is specifying more size than required when declaring an array a bad practice?

Speaking about static allocated arrays with size fixed at compile-time, specifying more size than required is not a bad practice in general. Of course, you will probably waste some memory but it is always a good decision to stay safe than to have real serious trouble when you need more memory or try to access memory beyond the bounds by accident which invokes undefined behavior.

However, if the amount of the waste size is enormous and the range between the possible sizes is drastically, then you should really use dynamic memory allocation instead. For example a case where you do not know if you need 10 or 100000 elements up-front and you allocate 100000 elements just to be safe. That would be kind of bad practice.

It is also better to use dynamic memory in this case because the stack isn't as large as the heap memory.

Short summary: If you really don't want to waste any memory and want to be safe, use dynamic memory allocation instead of anything else.

Ad
source: stackoverflow.com
Ad