Question: Consider the following buggy program, which allocates a 4-element array of integers, assigns and prints them, then uses realloc to add 4 more integers to

Consider the following buggy program, which allocates a 4-element array of integers, assigns and prints them, then uses realloc to add 4 more integers to the array, assigns and prints those, before freeing the array.

#include

#include

void main(int argc, char** argv) {

int* x = (int *) malloc(4 * sizeof(int));

int i;

for(i = 0; i < 4; i++) {

x[i] = i;

printf("X[%d] = %d ", i, x[i]);

}

x = (int *) realloc(x, 4 * sizeof(int));

for(i = 0; i < 8; i++) {

x[i] = i;

printf("X[%d] = %d ", i, x[i]);

}

free(x);

}

Correct the bug above.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!