0
0
Embedded Cprogramming~20 mins

sizeof and memory budgeting in Embedded C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of sizeof with arrays and pointers

What is the output of this C code snippet?

Embedded C
#include <stdio.h>

int main() {
    int arr[10];
    int *ptr = arr;
    printf("%zu %zu\n", sizeof(arr), sizeof(ptr));
    return 0;
}
A40 4
B40 8
C10 4
D10 8
Attempts:
2 left
💡 Hint

Remember that sizeof on an array gives total bytes, but on a pointer gives pointer size.

🧠 Conceptual
intermediate
2:00remaining
Memory budgeting for struct with padding

Given this struct, what is the total size in bytes on a system where int is 4 bytes and alignment is on 4-byte boundaries?

struct S {
  char a;
  int b;
  char c;
};
A9
B10
C12
D8
Attempts:
2 left
💡 Hint

Think about padding added to align int b and the struct size.

🔧 Debug
advanced
2:00remaining
Why does this memory budgeting code produce wrong size?

What error causes the wrong total size calculation in this code?

struct Data {
  char flag;
  double value;
};

int total_size() {
  return sizeof(char) + sizeof(double);
}
AIt ignores padding between <code>flag</code> and <code>value</code> causing underestimation
BIt uses wrong types in <code>sizeof</code> causing overestimation
CIt should use <code>sizeof(struct Data)</code> instead of summing members
DIt returns size in bits instead of bytes
Attempts:
2 left
💡 Hint

Think about how structs are aligned in memory.

📝 Syntax
advanced
2:00remaining
Which code correctly uses sizeof for memory allocation?

Which option correctly allocates memory for an array of 5 integers?

Aint *arr = malloc(5 * sizeof(arr));
Bint *arr = malloc(sizeof(int) * 5);
Cint *arr = malloc(5 * sizeof(int));
Dint *arr = malloc(sizeof(*arr) * 5);
Attempts:
2 left
💡 Hint

Consider what sizeof(arr) and sizeof(*arr) mean.

🚀 Application
expert
3:00remaining
Calculate total memory for nested structs

Given these structs, what is the total size of struct Container on a system where int is 4 bytes, char is 1 byte, and alignment is on 4-byte boundaries?

struct Inner {
  char x;
  int y;
};

struct Container {
  struct Inner a;
  char b;
};
A12
B10
C8
D16
Attempts:
2 left
💡 Hint

Calculate size of Inner first including padding, then add b with padding.