Subject: Unix Internals Topic: Memory

(Part I: Exploring the Memory Layout of a Struct)

  1. Program Listing:

1 /*

2 File: project.h

3 Course: CENG251

5 Date: Friday May 21, 2022 10:56 PM

6 */

7 #define _project_h

8 #pragma once

9

10 #include <stdlib.h>

11 #include <string.h>

12

13 //1. Create and declare your own data structure - mine is called project and its theme is based on rock climbing

14 struct PROJECT{

15 char beta[15]; //Odd sized char string

16 int grade;

17 int year;

18 char type[10];

19 float weight;

20 char sent;

  1. };

  1. Program Listing:

1 /*

2 File: climbing.c

3 Course: CENG251

5 Date: Friday May 21, 2022 11:08 PM

6 */

7

8 #include <stdio.h>

9 #include <stddef.h>

10 #include "project.h"

11

12 int main(int argc, char * argv[],char * envp[])

13 {

14 struct PROJECT climb;

15

16 //2. Write a program that determines sizeof each of your fields and the whole data structure

17 fprintf(stdout,"The size of beta is %zu\n", sizeof climb.beta);

18 fprintf(stdout,"The size of grade is %zu\n", sizeof climb.grade);

19 fprintf(stdout,"The size of year is %zu\n", sizeof climb.year);

20 fprintf(stdout,"The size of type is %zu\n", sizeof climb.type);

21 fprintf(stdout,"The size of weight is %zu\n", sizeof climb.weight);

22 fprintf(stdout,"The size of sent is %zu\n", sizeof climb.sent);

23 fprintf(stdout,"The size of a climbing project is %zu\n\n", sizeof climb);

24

25 //3. Determine the offsets of each of the fields in your struct

26 fprintf(stdout,"The offset of beta is %zu\n", offsetof(struct PROJECT,beta));

27 fprintf(stdout,"The offset of grade is %zu\n", offsetof(struct PROJECT,grade));

28 fprintf(stdout,"The offset of year is %zu\n", offsetof(struct PROJECT,year));

29 fprintf(stdout,"The offset of type is %zu\n", offsetof(struct PROJECT,type));

30 fprintf(stdout,"The offset of weight is %zu\n", offsetof(struct PROJECT,weight));

31 fprintf(stdout,"The offset of sent is %zu\n", offsetof(struct PROJECT,sent));

32

33 return 0;

34 }

Output:

Subject: Unix Internals Topic: Memory 1

The sum of the parts is smaller than the size of the whole data structure.

  1. (Code for this section is included in program listing above – starting at line 34.)

Subject: Unix Internals Topic: Memory 2


  1. Output:

Subject: Unix Internals Topic: Memory 3


The space saving occurred in fields beta and type, both of which are char type. Packing this program ensured that the alignment rule is ignored and therefore, the space was optimized by being compressed.

Subject: Unix Internals Topic: Memory 4