Search code examples
cpointerssegmentation-faultfwrite

C - fwrite dynamic array by a function, pointers


Im trying to fwrite() a dynamic array with a function. The problem are the pointers inside the fopen().

While successfully fwrite() the dynamic array to file, from the main function, when trying to move fwrite() to a separate function troubles occur with the pointers. In specific the pointers pointing to the array, which are located inside fwrite() within the function.

here is the relevant code.

main()
{
...
  unsigned char **pixels_array = NULL; //write this array to file
  allocateArray(&pixels_array);  //prepare array
  fillArray(&pixels_array);
  writeFile(&pixels_array);
  freeArray(&pixels_array); 
...
}

writeFile(unsigned char ***pixels_array)  //param is pointer to double pointer array
{
  ...
  FILE *file = fopen(output_filename, "wb"); //open file
  if (file == NULL)
  {
    printf(ERROR_OPEN_FILE_MSG);
    return ERROR_OPEN_FILE;
  }

  for(i = 0; i < height; i++) //writing row by row of the array to file
  {
    //PROBLEM
    //seg fault when running with current pointers to pixels_array in fwrite()
    fwrite((&(*(*pixels_array)))[i], sizeof(unsigned char) * padded_width, 1, file);
  }
  fclose(file);
}

allocateArray(unsigned char ***pixels_array)
{
  ...
  *pixels_array = (unsigned char**)malloc(height * sizeof(unsigned char*)); //image y coord.
  ...
  for(i = 0; i < height; i++)
  {
    //(allocate scanlines) image x coord., no sizeof(unsigned char*) because == 1
    (*pixels_array)[i] = (unsigned char*)malloc(width); 
    ...
  }
  ...
}

Solution

  • You get a seg fault when dealing with pointers when there are some errors in allocation ,so can yo provide your allocation function too?

    And if want to write a row to the file you can simply use:

     fwrite((*(pixels_array))[i],rest is same);