I was looking into structs in C when I noticed this oddity.  #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdint.h&gt;  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-&gt;start));     printf("Sizeof overflow: %d\r\n", sizeof(test-&gt;overflow));     printf("Sizeof controlledPointer: %d\n\r", sizeof(test-&gt;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 () 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!
1450
Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?
11055
I have a situation where I need to process large (many GB's) amounts of data as such:   build a large string by appending many smaller (C char*) strings trim the string convert the string into a C++ const std::string for processing (read only) repeat   The data in each iteration are independent.  My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.  Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?  Alternatively, could I use stringstreams or something similar to re-use a large buffer?  Edit: Thanks for the answers, for clarity, I think a revised question would be:  How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.
122420
I get a transmission over the network that's an array of chars/bytes. It contains a header and some data. I'd like to map the header onto a struct. Here's an example:  #pragma pack(1)  struct Header {     unsigned short bodyLength;     int msgID;     unsigned short someOtherValue;     unsigned short protocolVersion; };  int main() {     boost::array&lt;char, 128&gt; msgBuffer;     Header header;      for(int x = 0; x &lt; sizeof(Header); x++)         msgBuffer[x] = 0x01; // assign some values      memcpy(&amp;header, msgBuffer.data(), sizeof(Header));      system("PAUSE");          return 0; }   Will this always work assuming the structure never contains any variable length fields? Is there a platform independent / idiomatic way of doing this?  Note:  I have seen quite a few libraries on the internet that let you serialize/deserialize, but I get the impression that they can only deserialize something if it has ben previously serialized with the same library. Well, I have no control over the format of the transmission. I'm definitely going to get a byte/char array where all the values just follow upon each other.
30661
This is a question that was sparked by 's answer . Suppose I declare a class/struct like so: struct {      char A;     int B;     char C;     int D; };  Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing?  I'm asking because I had always assumed that the compiler can do whatever it wants with them. This leads into my next question.  If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly: struct {      char A;     char C;     int B;     int D; };  (I'm primarily asking about C++, but I'd be interested to hear the C answer as well) Related topics
84371
In ANSI C, offsetof is defined as below.  #define offsetof(st, m) \     ((size_t) ( (char *)&amp;((st *)(0))-&gt;m - (char *)0 ))   Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?
54729
I'm looking for a way to convert a preprocessor token to a string.  Specifically, I've somewhere got:  #define MAX_LEN 16   and I want to use it to prevent buffer overrun:  char val[MAX_LEN+1]; // room for \0 sscanf(buf, "%"MAX_LEN"s", val);   I'm open to other ways to accomplish the same thing, but standard library only.
97462
This has been something that has bothered me for ages now.  We are all taught in school (at least, I was) that you MUST free every pointer that is allocated.  I'm a bit curious, though, about the real cost of not freeing memory.  In some obvious cases, like when malloc is called inside a loop or part of a thread execution, it's very important to free so there are no memory leaks.  But consider the following two examples:  First, if I have code that's something like this:  int main() {     char *a = malloc(1024);     /* Do some arbitrary stuff with 'a' (no alloc functions) */     return 0; }   What's the real result here?  My thinking is that the process dies and then the heap space is gone anyway so there's no harm in missing the call to free (however, I do recognize the importance of having it anyway for closure, maintainability, and good practice).  Am I right in this thinking?  Second, let's say I have a program that acts a bit like a shell.  Users can declare variables like aaa = 123 and those are stored in some dynamic data structure for later use.  Clearly, it seems obvious that you'd use some solution that will calls some *alloc function (hashmap, linked list, something like that).  For this kind of program, it doesn't make sense to ever free after calling malloc because these variables must be present at all times during the program's execution and there's no good way (that I can see) to implement this with statically allocated space.  Is it bad design to have a bunch of memory that's allocated but only freed as part of the process ending?  If so, what's the alternative?
40847
I can create a literal long by appending an L to the value; why can't I create a literal short or byte in some similar way? Why do I need to use an int literal with a cast?  And if the answer is "Because there was no short literal in C", then why are there no short literals in C?  This doesn't actually affect my life in any meaningful way; it's easy enough to write (short) 0 instead of 0S or something. But the inconsistency makes me curious; it's one of those things that bother you when you're up late at night. Someone at some point made a design decision to make it possible to enter literals for some of the primitive types, but not for all of them. Why?
11872
How can I figure out the size of a file, in bytes?  #include &lt;stdio.h&gt;  unsigned int fsize(char* file){   //what goes here? }
84760
I am surprised that I can't initialize my fields in structs, why is it like that? Like:  struct MyStruct {     private int a = 90; }   but it's a complie time error. I don't know why it's a problem? Please explain this to me.
47168
I was trying to understand something with pointers, so I wrote this code:  #include &lt;stdio.h&gt;  int main(void) {     char s[] = "asd";     char **p = &amp;s;      printf("The value of s is: %p\n", s);     printf("The direction of s is: %p\n", &amp;s);      printf("The value of p is: %p\n", p);     printf("The direction of p is: %p\n", &amp;p);      printf("The direction of s[0] is: %p\n", &amp;s[0]);     printf("The direction of s[1] is: %p\n", &amp;s[1]);     printf("The direction of s[2] is: %p\n", &amp;s[2]);      return 0; }   When compiling it with gcc I get these warnings:  $ gcc main.c -o main-bin -ansi -pedantic -Wall -lm main.c: In function ‘main’: main.c:6: warning: initialization from incompatible pointer type main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’ main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’ main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’   (The flags for gcc are because I must be C89)  Why incompatible types of pointer? Isn't the name of an array a pointer to it's first element? So if s is a pointer to 'a', &amp;s must be a char **, no? And why do I get the other warnings? Do I have to cast the pointers with (void *) in order to print them?   And when running I get something like this:  $ ./main-bin The value of s is: 0xbfb7c860 The direction of s is: 0xbfb7c860 The value of p is: 0xbfb7c860 The direction of p is: 0xbfb7c85c The direction of s[0] is: 0xbfb7c860 The direction of s[1] is: 0xbfb7c861 The direction of s[2] is: 0xbfb7c862   How can the value of s and it's direction (and of course the value of p) be the same?
38175
For example: sizeof(char*) returns 4.  As does int*, long long*, everything that I've tried.  Are there any exceptions to this?
73598
I have a char array buffer that I am using to store characters that the user will input one by one.  My code below works but has a few glitches that I can't figure out:   when I execute a printf to see what's in Buffer, it does fill up but I get garbage characters at the end it won't stop at 8 characters despite being declared as char Buffer[8];   Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks.  char Buffer[8]; //holds the byte stream int i=0;  if (/* user input event has occurred */)  {         Buffer[i] = charInput;         i++;          // Display a response to input         printf("Buffer is %s!\n", Buffer);  }   Output:   tagBuffer is 1┬┬w! tagBuffer is 12┬w! tagBuffer is 123w! tagBuffer is 1234! tagBuffer is 12345! tagBuffer is 123456=! tagBuffer is 1234567! tagBuffer is 12345678!  tagBuffer is 123456789!
53355
I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work?  Edit: tokenizing using:  strtok(string, " ");   The code is like the following  pch = strtok (str," "); while (pch != NULL) {   printf ("%s\n",pch);   pch = strtok (NULL, " "); }
64558
I started learning about pointers in C++ and I figured I should educate myself a bit on how memory works and is accessed. I read that when we say a processor is 64-bit, it has a 64-bit register and can access 2^64 address locations. I also read that it can fetch 64/8, so 8 bytes of data at a time, but the data bus is not the same thing as the register right? Do they need to be the same size or does that just happen to be the case usually? And is it the size of the register or the data bus size that determines what we refer to it as, such as 32/64-bit? Also is there a difference between register size and address size?
13366
In , someone suggested in a  that I should not cast the result of malloc. i.e., I should do this: int *sieve = malloc(sizeof(int) * length);  rather than: int *sieve = (int *) malloc(sizeof(int) * length);  Why would this be the case?
100259
Is std::string size() a O(1) operation?  The implementation of STL I'm using is the one built into VC++