0

I'm trying to write and read a char three dimensional array, or said in other words an array of strings arrays.

I've already try to allocate the memory in each part of the array, but it keeps failing with the following error: Segment fault (core dumped)

/**
 * Create array to write
 */
char writed[2][2][512] = {{"Hello", "World"}, {"Bye", "World"}};
/**
 * Allocate memory
 */
char *** readed = (char ***)malloc(sizeof(char **) *2 * 2 * 512);
for (int z = 0; z < 2; z++) {
    readed[z] = (char **)malloc(sizeof(char **) * 2 * 512 );
    for (int y = 0; y < 2; y++) {
        readed[z][y] = (char *)malloc(sizeof(char) * 512); 
    }
}    
/**
 * Write array
 */
FILE *writeFile = fopen("strings", "wb");
fwrite(writed, 2 * 2 * 512, 2 * 512, writeFile);
fclose(writeFile);
/**
 * Read array
 */
FILE *readFile = fopen("strings", "rb");
fread(readed, 2 * 2 * 512, 2 * 512, readFile);
fclose(readFile);

1 Answers1

1

You have two different data structures here, each with a different layout.

writed is a 3 dimensional array of char, meaning that all of the memory of the array is contiguous. In contrast, readed is a pointer to an array of char **, each of which points to an array of char *,each of which points to an array of char, and none of those need be continuous.

To have a similar data structure, you need declare readed as a pointer to a 2D array and allocate space for enough of those for a 3D array:

char (*readed)[2][512] = malloc(2 * sizeof(char[2][512]));

Also, don't cast the return value of malloc.

You're also writing / reading way more than you need to:

fwrite(writed, 2 * 2 * 512, 2 * 512, writeFile);
...
fread(readed, 2 * 2 * 512, 2 * 512, readFile);

This says you're reading / writing 2 * 512 elements, each of which has size 2 * 2 * 512. You're only reading/writing 1 member of that size:

fwrite(writed, 2 * 2 * 512, 1, writeFile);
...
fread(readed, 2 * 2 * 512, 1, readFile);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • I tried to declare `readed` as you mention with out assign memory to each location of the array, but now the compiler fails with the error `free(): invalid pointer. Abort (core dumped)` – Alessandro Aguilar Feb 06 '19 at 21:31
  • @DanielAlessandroAguilar You should only `free` what you `malloc`, specifically `free(readed)` only. – dbush Feb 06 '19 at 21:32
  • I'm not calling `free` function, I just change the pointer declaration and delete the `for` that allocate memory in every position. – Alessandro Aguilar Feb 06 '19 at 21:35
  • @DanielAlessandroAguilar See my edit. You're writing / reading too many bytes. – dbush Feb 06 '19 at 21:39
  • Thanks, your edit solve my problem, I've thinking that thrid parameter to `fread` / `fwrite` was the size on bytes of every element on the array. – Alessandro Aguilar Feb 06 '19 at 21:45