recategorized by
646 views
4 votes
4 votes

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.
recategorized by

1 Answer

0 votes
0 votes

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.

Answer:

Related questions