Multiple choice

char ptr1[] = "Hello World"; char *ptr2 = malloc( 5 ); ptr2 = ptr1; What is wrong with the above code (assuming the call to malloc does not fail)?

  1. There will be a memory overwrite.

  2. There will be a memory leak.

  3. There will be a segmentation fault.

  4. Not enough space is allocated by the malloc.

  5. It will not compile.

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Initially, ptr2 points to dynamically allocated memory from malloc(5). The next statement reassigns ptr2 to point to ptr1, causing the reference to the original heap allocation to be lost without being freed, resulting in a classic memory leak.