The error is that you forgot to NUL terminate your string when filling directoryTmp
(in C strings are array of char
that by convention ends at the first char
whose value is 0
). Then, when strcat
try to append fname
it begins by iterating over directoryTmp
looking for a NUL character. As the array is initialized on the stack (at least I guess from the code snippet), its content is undefined, and strcat
scan past the end of the array which is undefined behavior (in your particular case this cause a segmentation fault).
So, the correct code would be:
/* specify the directory */
directoryTmp[0] = '/';
directoryTmp[1] = 'f';
directoryTmp[2] = 'i';
directoryTmp[3] = 'l';
directoryTmp[4] = 'e';
directoryTmp[5] = 's';
directoryTmp[6] = '/';
directoryTmp[7] = 0; // NUL terminate the string
Or as mentioned by others, just use strncpy
:
memset(directoryTmp, 0, sizeof(directoryTmp));
strncpy(directoryTmp, "/files/", sizeof(directoryTmp) - 1);
Note that strncpy
does not guarantee that the string will be NUL terminated, so we have to take care of that ourselves.