As others have said, in the snippet below there are two obviously wrong things:
- You do not allocate memory for
filename and size members of just allocated structures, - Your
memset() call uses the wrong size.
Your memset() call can be simplified and fixed:
memset(primary, 0, primarypcs * sizeof *primary);
There is another subtle problem in the code: the C-standard does not guarantee that all-bits-zero is a constant of a null pointer (i.e. NULL), so memset () is not the right way to set a pointer to NULL . A portable way to do what you want to do:
size_t i; for (i=0; i < primarypcs; ++i) { primary[i].filename = NULL; primary[i].size = NULL; }
To allocate memory for filename and size , it depends on what you want. Say you have determined that filename requires n bytes, and size needs m . Then your loop will change to something like this:
size_t i; for (i=0; i < primarypcs; ++i) { size_t n, m; primary[i].filename = malloc(n * sizeof *primary[i].filename); primary[i].size = malloc(m * sizeof *primary[i].size); }
You can omit the multiplication with sizeof *primary[i].filename and sizeof *primary[i].size from the above if you want: C guarantees that sizeof(char) is 1. I wrote above for completeness and for the case, when filename and size change types.
Note that if
filename is a string of length
k , for this you need
(k+1) bytes due to trailing
0 (so
n == k+1 above).
If I were to suggest that you want size to keep the length of the corresponding filename ? If so, size should not be char * , but a size_t . But since I do not know how you plan to use filename and size , I am not sure.
Be sure to check the return value of malloc() . It returns NULL for failure. I skipped checking from the above code for simplicity.
Your message is also marked as C ++, so if you want to use C ++, there is also a C ++ solution.
Alok singhal
source share