Open In App

Data Structure Alignment : How data is arranged and accessed in Computer Memory?

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. 
Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size. This increases the performance of the system due to the way the CPU handles memory. 
Data Structure Padding: Now, to align the data, it may be necessary to insert some extra bytes between the end of the last data structure and the start of the next data structure as the data is placed in memory as multiples of fixed word size. This insertion of extra bytes of memory to align the data is called data structure padding.
Consider the structure as shown below: 
 

struct 
{
char a;
short int b;
int c;
char d;
}

Now we may think that the processor will allocate memory to this structure as shown below: 
 

The total memory allocated in this case is 8 bytes. But this never happens as the processor can access memory with a fixed word size of 4 bytes. So, the integer variable c can not be allocated memory as shown above. An integer variable requires 4 bytes. The correct way of allocation of memory is shown below for this structure using padding bytes. 
 

The processor will require a total of 12 bytes for the above structure to maintain the data alignment. 
Look at the below C++ program: 
 

CPP




// CPP program to test
// size of struct
#include <iostream>
using namespace std;
 
// first structure
struct test1
{
    short s;
    int i;
    char c;
};
 
// second structure
struct test2
{
    int i;
    char c;
    short s;
};
 
// driver program
int main()
{
    test1 t1;
    test2 t2;
    cout << "size of struct test1 is " << sizeof(t1) << "\n";
    cout << "size of struct test2 is " << sizeof(t2) << "\n";
    return 0;
}


Java




// Java program to test size of struct
public class Main {
    // first structure
    static class Test1 {
        short s;
        int i;
        char c;
    }
 
    // second structure
    static class Test2 {
        int i;
        char c;
        short s;
    }
 
    // driver program
    public static void main(String[] args) {
        Test1 t1 = new Test1();
        Test2 t2 = new Test2();
        System.out.println("size of struct Test1 is " + Integer.BYTES * 2 );
        System.out.println("size of struct Test2 is " + Integer.BYTES + 4);
    }
}
 
//This code is generated by Chetan Bargal


C#




using System;
 
// Define the first structure
struct Test1
{
    public short s;
    public int i;
    public char c;
}
 
// Define the second structure
struct Test2
{
    public int i;
    public char c;
    public short s;
}
 
class Program
{
    static void Main(string[] args)
    {
        Test1 t1 = new Test1();
        Test2 t2 = new Test2();
         
        Console.WriteLine("Size of struct Test1 is " + System.Runtime.InteropServices.Marshal.SizeOf(t1));
        Console.WriteLine("Size of struct Test2 is " + System.Runtime.InteropServices.Marshal.SizeOf(t2));
    }
}


Output: 
 

size of struct test1 is 12
size of struct test2 is 8

For the first structure test1 the short variable takes 2 bytes. Now the next variable is int which requires 4 bytes. So, 2 bytes of padding are added after the short variable. Now, the char variable requires 1 byte but memory will be accessed in word size of 4 bytes so 3 bytes of padding is added again. So, a total of 12 bytes of memory is required. We can similarly calculate the padding for the second structure also. Padding for both of the structures is shown below: 
 

struct test1
{
short s;
// 2 bytes
// 2 padding bytes
int i;
// 4 bytes
char c;
// 1 byte
// 3 padding bytes
};
struct test2
{
int i;
// 4 bytes
char c;
// 1 byte
// 1 padding byte
short s;
// 2 bytes
};

Note: You can minimize the size of memory allocated for a structure by sorting members by alignment.
References : 
1) https://en.wikipedia.org/wiki/Data_structure_alignment 
2) https://stackoverflow.com/a/119134/6942060
 



Previous Article
Next Article

Similar Reads

Locking and Unlocking of Resources arranged in the form of n-ary Tree
Given an n-ary tree of resources arranged hierarchically such that height of tree is O(Log N) where N is total number of nodes (or resources). A process needs to lock a resource node in order to use it. But a node cannot be locked if any of its descendant or ancestor is locked. Following operations are required for a given resource node: islock()-
11 min read
Print the arranged positions of characters to make palindrome
You are given a string s (only lowercase alphabet) with length n. Print the position of every character of the string it must acquire so that it will form a palindromic string. Examples: Input : c b b a a Output : 3 1 5 2 4 To make string palindrome 'c' must be at position 3, 'b' at 1 and 5, 'a' at 2 and 4. Input : a b c Output : Not Possible Any p
7 min read
Check if elements of an array can be arranged in a Circle with consecutive difference as 1
Given an array of [Tex]N [/Tex]numbers. The task is to check if it is possible to arrange all the numbers in a circle so that any two neighboring numbers differ exactly by 1. Print "YES" if it is possible to get such arrangement and "NO" otherwise. Examples: Input: arr[] = {1, 2, 3, 2} Output: YES The circle formed is: 1 2 2 3 Input: arr[] = {3, 5,
3 min read
Check if elements of an array can be arranged satisfying the given condition
Given an array arr of N (even) integer elements. The task is to check if it is possible to reorder the elements of the array such that: arr[2*i + 1] = 2 * A[2 * i] for i = 0 ... N-1. Print True if it is possible, otherwise print False. Examples: Input: arr[] = {4, -2, 2, -4} Output: True {-2, -4, 2, 4} is a valid arrangement, -2 * 2 = -4 and 2 * 2
5 min read
Count of sub-arrays whose elements can be re-arranged to form palindromes
Given an array arr[] of size n. The task is to count the number of possible sub-arrays such that their elements can be re-arranged to form a palindrome. Examples: Input: arr[] = {1, 2, 1, 2} Output: 7 {1}, {2}, {1}, {2}, {1, 2, 1}, {2, 1, 2} and {1, 2, 1, 2} are the valid sub-arrays.Input: arr[] = {1, 2, 3, 1, 2, 3, 4} Output: 11 Approach: There ar
7 min read
Count non-adjacent subsets from numbers arranged in Circular fashion
Given that N people are sitting in a circular queue numbered from 1 to N, the task is to count the number of ways to select a subset of them such that no two consecutive are sitting together. The answer could be large, so compute the answer modulo 109 + 7. Note that an empty subset is also a valid subset. Examples: Input: N = 2 Output: 3 All possib
5 min read
Check if elements of array can be arranged in AP, GP or HP
Given an array arr[] of N integers. The task is to check whether by arranging the elements of the array, is it possible to generate an Arithmetic Progression, Geometric Progression or Harmonic Progression. If possible print "Yes", with the type of Progression or Else print "No".Examples: Input: arr[] = {2, 16, 4, 8} Output: Yes, A GP can be formed
12 min read
Puzzle | Connect 9 circles each arranged at center of a Matrix using 3 straight lines
Consider 9 circles each arranged at the center of cells of a 2-D matrix of shape 3*3. Draw 3 straight lines without removing pen from paper such that each of the 9 circles is in contact with at least one line. Solution: A similar problem is present here Connect 9 dots using 4 lines. The difference from above problem is that here there are 9 circles
1 min read
Count number of ways in which following people can be arranged
Given integers X and Y representing X girls and Y boys, the task is to count the number of ways arranging X girls and Y boys such that girls always stay together and two boys from Y refuse to stay consecutive. Print the answer modulo 109 + 7. Examples: Input: X = 2, Y = 2Output: 4Explanation: Let's say girls are G1 and G2 and Boys are B1 and B2, co
6 min read
Check if an array can be Arranged in Left or Right Positioned Array
Given an array arr[] of size n&gt;4, the task is to check whether the given array can be arranged in the form of Left or Right positioned array? Left or Right Positioned Array means each element in the array is equal to the number of elements to its left or number of elements to its right. Examples : Input : arr[] = {1, 3, 3, 2} Output : "YES" This
8 min read
Article Tags :
Practice Tags :