I was looking into structs in C when I noticed this oddity.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
struct vulnStruct {
char start[20];
char overflow[10];
char *controlledPointer;
};
int main(int argc, char *argv[]){
struct vulnStruct *test = malloc(sizeof(struct vulnStruct));
printf("Sizeof vulnStruct: %d\r\n", sizeof(struct vulnStruct));
printf("Sizeof start: %d\r\n", sizeof(test->start));
printf("Sizeof overflow: %d\r\n", sizeof(test->overflow));
printf("Sizeof controlledPointer: %d\n\r", sizeof(test->controlledPointer));
free(test);
return 0;
}
When compiled this program should output the sizeof the vulnStruct and its elements. Manually adding up the struct shows that it should be 38 bytes long however when this program is run it shows that the struct's size is instead 40 bytes long. At first I thought it was just padding for the struct as answered here (Size of a structure in C) however, when I add a 2 byte field (uint16_t) to the end of the struct in an attempt to fill the padding it just increases the struct by 2 bytes. Is this because the controlledPointer is being padded to 10 bytes by the compiler and won't let anything else use that space or is there something like a canary at the end that is taking up the space. If it is just padding is there anyway to arrange the elements so that the padding can be used by another field?
EDIT: It would probably help if I get the output of the program as well
Sizeof vulnStruct: 40
Sizeof start: 20
Sizeof overflow: 10
Sizeof controlledPointer: 8
Thanks in advance!