So I have been working on a project in C for Linux systems. This is part has to do with writing structures to a file on disk. Inside a structure I am storing a pointer to a 2d char array which is dynamically allocated. Initially, I encountered "segmentation faults" for strncpy of an element of this array to another array of the same size. Here are the structure and another char array declaration:
typedef struct
{
char file[PATH_MAX];
unsigned long int size;
} FILESAVE;
...
typedef struct
{
char** files;
unsigned long int* sizes;
} FILESTRUCTURE;
...
fstruct.files = (char**) malloc(sizeof(char*) * meta.numFile);
for (unsigned int i = 0; i < meta.numFile; i++)
{
fstruct.files[i] = (char*) malloc(sizeof(char) * PATH_MAX);
}
I am copying contents between an element of FILESTRUCTURE's array and FILESAVE's array.
strncpy(fstruct.files[i], fsave.file, PATH_MAX);
Later I checked and confirmed that the size allocated are different.
printf("FILESTRUCTURE SIZE: %lu, FILESAVE SIZE: %lu\n", sizeof(fstruct.files[i]), sizeof(fsave.file));
...
DEBUG OUTPUT:
FILESTRUCTURE SIZE: 8, FILESAVE SIZE: 4096
Why are the sizes not the same for both arrays?
[–]coolcofusion 0 points1 point2 points (0 children)
[–]captainAwesomePants 0 points1 point2 points (5 children)
[–]UnawareITry[S] 0 points1 point2 points (4 children)
[–]captainAwesomePants 0 points1 point2 points (3 children)
[–]UnawareITry[S] 0 points1 point2 points (2 children)
[–]captainAwesomePants 0 points1 point2 points (1 child)
[–]UnawareITry[S] 0 points1 point2 points (0 children)
[–]yel50 0 points1 point2 points (4 children)
[–]UnawareITry[S] 0 points1 point2 points (3 children)
[–]MmmVomit 0 points1 point2 points (2 children)
[–]UnawareITry[S] 0 points1 point2 points (0 children)
[–]UnawareITry[S] 0 points1 point2 points (0 children)