-
Structure padding
Hi,
I write a simple program to understand structure padding.
The code is
Code:
#include <stdio.h>
# include <string.h>
int main()
{
struct test
{
char char1[4];
char char2[2];
}n = {"AB","DCE"};
printf("%s",n.char2);
return 0;
}
I run this program, and i expect the out will come DCE due to structure padding.
But this program give unexpected output "DC@".
This may due to garbage value @ is coming. but i run the same program in different computer and i get the same output.
Again, i modify my program like,
Code:
#include <stdio.h>
# include <string.h>
int main()
{
struct test
{
char char1[4];
char char2[2];
}n;
strcpy(n.char1,"AB");
strcpy(n.char2,"DEF");
printf("%s",n.char2);
return 0;
}
Here i get the output "DEF" as expected.
So, what the difference between above two program.
Sorry for my English,
Thanks
-
The string literal "DCE" is actually four characters (the representation in memory of the characters 'D', 'C', 'E', and a character with value zero (which marks the end of the string). strcpy() copies up to and including that zero character.
Attempting to copy four characters into an array of length two will always write past the end of that array. Your first program writes past the end of n.char2 by initialising it with the string "DCE". The second program does the same with the call of strcpy(n.char2, "DEF").
The results of writing past the end of any array results in what the C standard describes as "undefined behaviour". The term "undefined behaviour" has a very specific meaning in the standard - if code exhibits undefined behaviour, anything is allowed to happen. That can include reformatting your hard drive, producing output you expect, producing output you don't expect, producing no output, producing the output you are seeing, .... Any result is technically correct.
-
You are doing bad things in both variants. You are writing to an array index that is out of bounds. Padding is something that you should not take advantage of. Use the sizeof operator to check if padding happens. That's safe. Check the size of test, if it's not 6 but maybe 8 then it was padded. If it's 6, it wasn't.
-
To understand structure padding you should print out the addresses of the structure elements and see if they always progress as the size of the elements. But in your example using two char arrays may not show this especially since they're even length. Try mixing int, char (odd lengths), long, etc.
-
In GCC you can compile with the -Wpadded flag, which gives a warning when padding occurs.