Memory allocated is 5 bytes, but the string "Hello World" needs 12 bytes (11 chars + 1 null terminator).
Step 2: Understand consequences of insufficient memory
Copying a larger string into smaller allocated space causes buffer overflow and undefined behavior.
Final Answer:
Memory allocated is too small for the string -> Option A
Quick Check:
Allocated size < string length = Memory allocated is too small for the string [OK]
Hint: Allocate enough space including null terminator [OK]
Common Mistakes:
Ignoring string length vs allocated size
Not checking malloc return value
Assuming strcpy auto-expands memory
5. You want to allocate memory for an array of 5 integers, initialize them to zero, and then safely release the memory. Which code snippet correctly implements this flow?
hard
A. int *arr = malloc(5 * sizeof(int));
for(int i=0; i<5; i++) arr[i] = 0;
B. int arr[5];
for(int i=0; i<5; i++) arr[i] = 0;
C. int *arr = calloc(5, sizeof(int));
free(arr);
D. int *arr = malloc(5);
memset(arr, 0, 5 * sizeof(int));
free(arr);
Solution
Step 1: Understand memory allocation and initialization
calloc allocates and initializes memory to zero automatically, perfect for this task.
Step 2: Check safe memory release
free(arr); correctly releases the allocated memory after use.
Final Answer:
int *arr = calloc(5, sizeof(int));
free(arr); -> Option C
Quick Check:
calloc zero-initializes and malloc does not [OK]
Hint: Use calloc for zero-initialized memory allocation [OK]
Common Mistakes:
Using malloc without initializing memory
Allocating too little memory
Not freeing dynamically allocated memory
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.