247 views

Consider below two program fragments.

Assume malloc is always successful, and sizes are as follows -

sizeof (int *)=8 bytes
sizeof ( double)=8 bytes
sizeof ( char )=1 byte
sizeof ( int )=4 byte

Program 1
int **p;
p = (int **)malloc( 4 * sizeof(int) );
for (int i = 0; i < 4; i++) {
p[i] = (int *)malloc( sizeof(int) );
}


Program 2
int *array = malloc(n);
for (int i=0; i<n; i+=1) array[i]=0;

Which of the following statement is correct -

1. Program $1$ may produce a run time error, but Program $2$ will run fine.
2. Program $2$ may produce a run time error, but Program $1$ will run fine.
3. Both programs will always run fine.
4. Both programs may produce run time errors.

edited

In program $1$ –

We’re allocating $4*4=16B$ and using $4*8=32B$.

In program $2$ –

We’re allocating $nB$ and using $4nB$.

Can you please explain how we are saying 4nB, in program 2.
In program $2$, we are accessing $n$ ints and each int takes $4B$. So, in total we're accessing $4nB$.

But we've originally allocated only $nB$. Hence, it may lead to run time error.

In program 1:

Memory allocated in p $= 4 * sizeof(int) = 4 * 4 = 16 bytes$

Each p[i] requires $sizeof(*p) = sizeof(int *) = 8 bytes$ of memory. We have allocated 16bytes, so only p[0] and p[1] are valid addresses.

p[2] and p[3] are beyond the memory allocated and hence, may cause run time error.

Similarly in program 2:

Memory allocated is n bytes but we are trying to access total 4n bytes worth of memory which is beyond the memory allocated. Hence, may cause run time error.

by

edited
In programme 2: how are you saying that we are trying to access 4n bytes.. is it due to assigning 0 to the array in each iteration.

As we are not assigning any integer variable seperately.
edited by

What is "it" in your doubt? Can you kindly elaborate the doubt? @P SHANMUKHA SHARMA

1 vote