Arista Networks Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
The standard doesn't even define how much space an int takes, so it definitely doesn't define the size of this struct. Perhaps a good answer would be sizeof (char) + sizeof (int) + sizeof (double) + sizeof (void*) + possibly some space for alignment. I think your interviewer wants to see that you understand that the standard doesn't strictly define the size of things like this and that you know what alignment is.
A char is 1 byte (well, not quite: it's 1 word, which is usually 1 byte), and on a typical system an int is 4 bytes and a double is 8 bytes. On a typical 64-bit system, the pointer would be 64 bits, or 8 bytes (if this question asked about a 32-bit system, the pointer would typically be 4 bytes). So the total would then come to 21, which would probably be aligned to the nearest 8 and be 24.
It should be:
sizeof(char) + padding here + sizeof(int) + sizeof(double) + sizeof(void *)
In my 32 bit system it comes to: 1+3+4+8+4 = 20 bytes
On a 32 bit machine, this will be 20 bytes only i suppose. Though a double is of size 8 bytes, it needs only a 4 byte alignment. Even if it is aligned on a 8 byte boundary, it would need two memory fetch. Thus the size is going to be 20 bytes for a 32 bit machine. For a 64 bit machine, it will be 24 bytes
due byte padding the bits would be aligned multiple of four bytes.hence total bytes would be 24. byte padding is done for optimization by processor.
I would be careful about saying the answer is any specific value...see my answer for the reasoning behind that. I agree that 24 is likely to be the size, though.
The explanation in the article you refer to is not accurate. For this example, on Win 7 x64 and Linux x64, I do get 24, but on Linux x86, I get 20.
Then the real question becomes: why do we need a[0]? :-) :-) :-).
In certain situation in Arista network, this a[0] comes in handy.
The a[0] is trick to allocate variable size buffer at the end of the structure. E.g., if you need 20 bytes buffer in the a[], you would do something like
struct s *s1 = malloc(sizeof(struct s) + 20 * sizeof(int));
This would enable you to allocate both the structure and the buffer in a single malloc call(and also allow you to free it in one call). Instead of doing something like
struct s * s1 = malloc(sizeof(struct s));
s->a = malloc(20 * sizeof(int));
and in free
free(s->a);
free(s);
It's commonly used technique to prevent memory leaks(people forgetting to free a and just freeing s)
Ofcourse, this assumes the member a is defined as
int *a;
If we understanding padding correctly here the largest is double hence it will take them and multiply number of elements (except the a[0] as there is no array) hence answer is 24
- howaboutthis March 21, 2012if we have a[1] the answer will be 32.