OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

18.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

(C Question) Correct the code snippet

How can the issue in the following code be solved? Select all that apply.

int* add_numbers(int, int);
void main()
{
  int* p;
  p = add_numbers(1, 3);
}
int* add_numbers(int a, int b)
{
  int* sum = (int*) malloc (16);
  *sum = a + b;
  return sum;
}

Pick ONE OR MORE options

Choose one option.
Show answer & explanation
Answer: A. Defining the function add_numbers above main function

The code has two issues: (1) the function add_numbers is called before it is defined (forward declaration exists but definition comes after main), and (2) memory allocated by malloc is never freed, causing a memory leak. Option A fixes the declaration/definition ordering issue. Option C addresses the critical memory leak by deallocating the allocated memory when it's no longer needed. Option B (static) and Option D (global) do not solve the actual problems—static doesn't help with the scope issue, and making sum global introduces unnecessary global state without fixing the core issues.

Step-by-step Derivation:
Analysis of the code issues:

  1. Forward Declaration Issue: The function add_numbers is declared at the top but defined after main(). While the forward declaration allows the code to compile in some environments, best practice is to define the function before main() or place the full definition before main().

  2. Memory Leak: malloc(16) allocates 16 bytes on the heap, stores the sum, and returns the pointer. However, the pointer p in main() never calls free(p), so this memory is never deallocated—a memory leak.

  3. Evaluating Options:

    • A (Correct): Moving the function definition before main() or ensuring the definition appears before main() is a proper practice that avoids potential linking issues.
    • B (Incorrect): Making sum static would make it persist across function calls but doesn't address the memory leak or scope issues.
    • C (Correct): Adding free(p); in main() after the function call deallocates the memory and prevents the leak.
    • D (Incorrect): Making sum global introduces poor design and doesn't solve the core issues.

Correct fixes: Apply both A and C—reorganize function definition order and add proper deallocation.