Memory Allocation Questions
Practice Memory Allocation MCQs with answers and explanations. Page 1 of 1.
Category
C Programming
Topic
Memory Allocation
Page
1 / 1
Mode
Practice
Questions
Open any question to view the answer and explanation.
C memory lifetime — what is printed when returning a pointer to a local array?
/* program */
#include<stdio.h>
#include<string.h>
int main()
{
char *s;
char *fun();
s = fun();
printf("%s
", s);
return 0;
}
char fun()
{
char buffer[30];
strcpy(buffer, "RAM");
return buffer; / returning address of a local array */
}
Predict the output.
Open
View answer
C dynamic allocation — how many bytes are reserved by this call?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int p;
p = (int ) malloc(256 * 256);
if (p == NULL)
printf("Allocation failed");
return 0;
}
Assume the request succeeds. How many bytes does malloc attempt to reserve?
Open
View answer
C unions — what is printed after storing a float in a union and reading it back?
#include<stdio.h>
#include<stdlib.h>
int main()
{
union test
{
int i;
float f;
char c;
};
union test *t = (union test *) malloc(sizeof(union test));
t->f = 10.10f;
printf("%f", t->f);
return 0;
}
Assume malloc succeeds.
Open
View answer
C on a 16-bit platform — what does sizeof(p) print for an int* allocated with malloc?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int p = (int ) malloc(20);
printf("%d
", (int) sizeof(p));
free(p);
return 0;
}
Assume a classic 16-bit memory model.
Open
View answer
C after free — what does printing the pointer value show?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p = (int ) malloc(20); / Assume, for illustration, p held address 1314 /
free(p);
printf("%u", p); / Printing pointer with %u is itself non-portable /
return 0;
}
What will be the output conceptually?
Open
View answer
C pointers to arrays — sizes when int is 2 bytes.
#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
", (int) sizeof(p), (int) sizeof(*p));
return 0;
}
Assume sizeof(int) = 2. What is printed?
Open
View answer
C pointer-to-array allocation — total bytes allocated when int is 2 bytes.
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int (p)[MAXCOL];
p = (int ()[MAXCOL]) malloc(MAXROW * sizeof(*p));
return 0;
}
Assume sizeof(int) = 2. How many bytes does malloc request?
Open
View answer
Practice smarter
Solve a few questions daily and revisit weak topics regularly to improve accuracy.