ProgrammingC developer

What happens when a structure is passed to a function by value and how does it affect the performance and semantics of the program?

Pass interviews with Hintsage AI assistant

Answer

In the C language, when a structure is passed to a function by value, a complete copy of the structure is created in the temporary memory area (usually on the function's stack). This means that any changes made inside the function do not affect the original instance of the structure outside the function.

When passing large structures by value, you encounter time and memory overhead due to the need to copy all the members of the structure. Therefore, the standard practice is to pass a pointer to the structure:

#include <stdio.h> struct Data { int arr[1000]; int flag; }; void modify_by_value(struct Data d) { d.flag = 10; // Only changes the local copy } void modify_by_pointer(struct Data *d) { d->flag = 20; // Changes the original } int main() { struct Data data = { {0}, 0 }; modify_by_value(data); // data.flag == 0 modify_by_pointer(&data); // data.flag == 20 return 0; }

Advantages of passing by pointer:

  • No overhead for copying large amounts of data
  • Can modify the original structure

Disadvantages of passing by value:

  • Temporal and spatial overhead for copying
  • Increased stack consumption (especially on microcontrollers)

Trick Question

What happens if a function returns a structure by value? What are the risks?

Answer:

In C, you can return a structure by value from a function, for example:

struct Point { int x, y; }; struct Point make_point(int x, int y) { struct Point p = {x, y}; return p; // returns a copy }

The main risk is performance: a copy of the structure is created and returned. Additionally, if one mistakenly returns the address of a local variable, the structure may point to invalid memory:

struct Point* bad() { struct Point p = {1, 2}; return &p; // error: returning the address of a local variable }

Examples of real errors due to ignorance of the nuances of the topic


Story

On embedded devices with small stacks, a developer passed a large structure (1 KB) by value, causing a stack overflow and sporadic system failures. Investigation showed that the copying of each structure led to stack memory depletion at deep call nesting.


Story

In a corporate server system, a programmer returned a pointer to a local structure, leading to access to "dangling" pointers after exiting the function. This manifested as a critical segmentation fault in production with rare reproducibility.


Story

In an Open Source project, performance dropped sharply after switching to a function that returned a by-value complex structure with internal arrays. The profiler identified CPU time overhead due to unnecessary multiple copies of structures.