Which of the following is the correct way to dynamically allocate memory for...
IBM technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Which of the following is the correct way to dynamically allocate memory for one-dimensional integer array 'x' of size 10?
Pick ONE option
Show answer & explanation
Answer: D. x = (int*) malloc(10 * sizeof(int));
The malloc() function takes exactly one argument: the number of bytes to allocate. To allocate space for 10 integers, you must multiply the count (10) by the size of each integer (sizeof(int)). Option D is correct because it properly calculates the total memory needed. Option A allocates only 10 bytes (insufficient for 10 integers). Option B is syntactically invalid—malloc() accepts only one argument, not two. Option C has invalid syntax with 'int 10' as a parameter.
Step-by-step Derivation:
Step-by-step analysis:
- malloc() signature: void* malloc(size_t size) — takes ONE argument (total bytes)
- For an array of 10 integers: total_bytes = 10 * sizeof(int)
- On most systems, sizeof(int) = 4 bytes, so we need 10 * 4 = 40 bytes
- Checking each option:
- A: malloc(10) allocates only 10 bytes → WRONG (too small)
- B: malloc(10, sizeof(int)) → WRONG (malloc() doesn't accept 2 arguments)
- C: malloc(int 10, sizeof(int)) → WRONG (syntax error, invalid parameter)
- D: malloc(10 * sizeof(int)) allocates 40 bytes (correct total) → CORRECT
- The cast (int*) is optional in C but good practice for clarity.