C problems: 1: Consider the problem of padding the following structure, and answ
ID: 3885335 • Letter: C
Question
C problems:
1:
Consider the problem of padding the following structure, and answer the questions below. Assume that you are compiling on a system with a 32-bit architecture.
struct BMP_Header {
char signature[2];
int size;
char reserved1;
enum offset_type offset_pixels;
};
a) What is the size of this struct as defined?
b) How much space would be wasted with word length padding?
2:
Consider the following fragment of code which is meant to add two together two xy points, and answer the two questions below:
struct point {
int x;
int y
};
struct point* add_points(struct point* p1, struct point* p2) {
struct point result;
result.x = p1->x + p2->x;
result.y = p1->y + p2->y;
return &result;
}
Most of the time function will appear to work fine, but then later there will be an issue with the result point's data changing unexpectly.
a) What is the problem?
b) How it can be fixed?
Explanation / Answer
1.Size of the structure is 2+4+1+4 = 11
Actual allocated size will be 12 as a multiple of 4. So due to padding only one byte is getting wasted.
2. The problem here is the address of the local variable is being returned from
the function.This is not correct as local variable are non existent after the function call. So correct thing will be allocating the memory from the heap wth malloc which will stay after the function call also.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.