...
| Code Block |
|---|
int array[]; |
This array is called an incomplete type because the size is unknown. If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. At the end of its initializer list, the array no longer has incomplete type.
...
While these declarations work fine when the size of the array is known at compile time, it is not possible to declare an array in this fashion when the size can be determined only at runtime. The C Standard adds support for variable length arrays or arrays whose size is determined at runtime. Before the introduction of variable length arrays in C99, however, these "arrays" were typically implemented as pointers to their respective element types allocated using malloc(), as shown in this example.:
| Code Block |
|---|
int *dis = (int *)malloc(ARRAY_SIZE * sizeof(int)); |
...
It is important to retain any pointer value returned by malloc() so that the referenced memory may eventually be deallocated. One possible way of preserving such a value is to use a constant pointer.:
| Code Block |
|---|
int * const dat = (int * const)malloc( ARRAY_SIZE * sizeof(int) ); /* ... */ free(dat); |
...
| CERT C++ Secure Coding Standard | ARR00-CPP. Understand when to prefer vectors over arrays |
| MITRE CWE | CWE-119, Failure to constrain operations within the bounds of an allocated memory buffer CWE-129, Unchecked array indexing |
...