c - How are char ** objects saved? -
today, asked me, how char **
objects saved in memory or in binary files. tested following code snippet:
char **array = (char *)malloc(3 * sizeof(char *)); array[0] = "foo"; // length: 3 array[1] = "long string"; // length: 11 array[2] = "bar"; // length: 3 => full length: 17 int length = 17;
i write array file:
file *file = fopen(...); fwrite(array, length, 1, file); fclose(file);
the great thing when read again array file following code, string lengths read without saving more 17 bytes.
file *file = fopen(...); int length = 17; char **array = (char *)malloc(length); int index = 0; int parsedlength = 0; while (parsedlength < length) { char *string = array[index]; int stringlength = strlen(string); printf("%i: \"%s\" (%i)\n", index, string, stringlength); parsedlength += stringlength; ++index; }
i output equals:
0: "foo" (3) 1: "long string" (11) 2: "bar" (3)
how compiler know, how long each string in array is?
pointers saved file numbers (or better addresses) fact code works illusion created fact saving , loading them inside same program in same run (so since these string literals, address fixed in data segment).
what doing wrong because array's layout in memory following (i'm assuming 4 bytes pointers):
xxxxxxxx yyyyyyyy zzzzzzzz ( = 12 bytes) ^ ^ ^ | | pointer "bar" | pointer "long string" pointer "foo"
but saving 17 bytes onto file, 12 of memory addresses.
to correctly save strings in file need store whole data contained , length. like:
for (int = 0; < array_length; ++i) { char *string = array[i]; unsigned int length = strlen(string); fwrite(&length, sizeof(unsigned int), 1, out); fwrite(string, sizeof(char), length, out); } (int = 0; < array_length; ++i { unsigned int length; fread(&length, sizeof(unsigned int), 1, in); array[i] = calloc(sizeof(char), length); fread(array[i], sizeof(char), length, in); }
Comments
Post a Comment