ProgrammingC Developer

Please describe in detail the mechanism of passing arrays to functions in the C language. What are the risks associated with this model, and how can one properly organize safe work with arrays inside functions?

Pass interviews with Hintsage AI assistant

Answer

In C, arrays are not passed to functions by value. When an array is passed as an argument, a pointer to the first element of the array is actually passed to the function. This leads to the function modifying the original array rather than a copy of it.

For example:

void fillArray(int arr[], int n) { for (int i = 0; i < n; ++i) arr[i] = i*i; } int main() { int myarr[5]; fillArray(myarr, 5); // ok }

Inside the function:

  • it is impossible to know the size of the original array through sizeof(arr) — this will return the size of the pointer, not the array.
  • you can only work with the chunk of memory whose size you have explicitly passed.

To work correctly and safely with arrays, you can do the following:

  • always explicitly pass the size of the array as a separate argument;
  • use constants or wrapper macros for sizes;
  • if you need to protect the array from modifications, pass const int *arr.

Trick Question

Question: Is it possible to find out the size of the original passed array inside the function using the argument int arr[] via sizeof(arr)?

Answer: No, it is not! sizeof(arr) inside the function will return the size of the pointer type (for instance, 4 or 8 bytes), not the size of the array.

Example:

void f(int arr[]) { printf("%zu ", sizeof(arr)); // size of pointer, not array! } int main() { int x[10]; f(x); // Usually outputs 8 (x86_64) or 4 (x86) }

Examples of Real Errors


Story

In an industrial project, the array copying functions attempted to calculate the length of the array on the fly using sizeof(arr)/sizeof(int) inside the function. In practice, this led to copying only part of the array since the size always equaled 1 (8/8), and the data got overwritten unpredictably.


Story

In a network application, a data sending function accepted a buffer as an array without explicitly specifying its size, causing the entire buffer not to be sent on time, or reading garbage out of the array's bounds, which caused transmission errors and connection instability.


Story

When writing a library for image processing, the programmer did not provide the function for coloring an array of images with a required size parameter. This led to a buffer overflow and crashed the program on certain inputs, which was only discovered during integration testing on a large image.