LearnFrenzy
Sign in Take a free test

Memory Allocation · Exercise 2 of 4

Memory Allocation Predict the Output

  • 12 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Read each program and choose what it prints. Every program was compiled with AddressSanitizer and run on a 64-bit system, so the answers are the real output.

Question 11 Medium

What is the output of the following C program on a 64-bit system?

main.c
#include <stdio.h>
#include <stdlib.h>

struct node {
    int v;
    struct node *next;
};

int main(void) {
    struct node *n = calloc(1, sizeof *n);
    if (n == NULL)
        return 1;
    printf("%d %s\n", n->v, n->next == NULL ? "NULL" : "set");
    free(n);
    return 0;
}
A 0 set
B garbage set
C 0 NULL
D Compilation error
Question page & discussion
Question 12 Hard

What is the output of the following program, compiled as C23 on a 64-bit system?

main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    auto p = (int *) malloc(3 * sizeof(int));   /* C23 auto: p is int * */
    if (p == nullptr)
        return 1;
    p[0] = 1;
    p[1] = 2;
    p[2] = p[0] + p[1];
    printf("%d %zu\n", p[2], sizeof p);
    free(p);
    p = nullptr;
    return 0;
}
A 3 12
B 3 4
C 3 8
D Compilation error
Question page & discussion
Up next · Exercise 3Find the Error8 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links