Exercise: Memory Allocation
Questions for: Memory Allocation
Point out the correct statement will let you access the elements of the array using 'p' in the following program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, j;
int(*p)[3];
p = (int(*)[3])malloc(3*sizeof(*p));
return 0;
}
A:
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d", p[i+j]);
}
B:
for(i=0; i<3; i++)
printf("%d", p[i]);
C:
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d", p[i][j]);
}
D:
for(j=0; j<3; j++)
printf("%d", p[i][j]);
Answer: C
No answer description is available. Let's discuss.
Point out the error in the following program.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *ptr;
*ptr = (char)malloc(30);
strcpy(ptr, "RAM");
printf("%s", ptr);
free(ptr);
return 0;
}
A:
Error: in strcpy() statement.
B:
Error: in *ptr = (char)malloc(30);
C:
Error: in free(ptr);
D:
No error
Answer: B
Answer: ptr = (char*)malloc(30);
Discuss About this Question.
Point out the error in the following program.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a[3];
a = (int*) malloc(sizeof(int)*3);
free(a);
return 0;
}
A:
Error: unable to allocate memory
B:
Error: We cannot store address of allocated memory in a
C:
Error: unable to free memory
D:
No error
Answer: B
We should store the address in a[i]
Discuss About this Question.
How many bytes of memory will the following code reserve?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p = (int *)malloc(256 * 256);
if(p == NULL)
printf("Allocation failed");
return 0;
}
A:
65536
B:
Allocation failed
C:
Error
D:
No output
Answer: B
Hence 256*256 = 65536 is passed to malloc() function which can allocate upto 65535. So the memory allocation will be failed in 16 bit platform (Turbo C in DOS).
If you compile the same program in 32 bit platform like Linux (GCC Compiler) it may allocate the required memory.
Discuss About this Question.
Assume integer is 2 bytes wide. What will be the output of the following code?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int (*p)[MAXCOL];
p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
printf("%d, %d\n", sizeof(p), sizeof(*p));
return 0;
}
A:
2, 8
B:
4, 16
C:
8, 24
D:
16, 32
Answer: A
No answer description is available. Let's discuss.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.