I want to add a directory to a filename in c but i get an error like:
Segmentation fault (core dumped)
Here is my code:
char fname[255];
char directoryTmp[262];
/*Working Code for entering the filename fname with fgets() */
...
/* specify the directory */
directoryTmp[0] = "/";
directoryTmp[1] = "f";
directoryTmp[2] = "i";
directoryTmp[3] = "l";
directoryTmp[4] = "e";
directoryTmp[5] = "s";
directoryTmp[6] = "/";
/* Copy fname at the end of directoryTmp */
strcat(directoryTmp,fname);
/* new fname with the directory, should look like: "/files/afilename */
for(i=0;i<strlen(directoryTmp);i++){
fname[i] = directoryTmp[i];
}
//edit
OK this is my new code, but I still get the same error code:
char fname[255];
char directory[262];
directory[sizeof(directory) - 1] = '\0';
strncpy(directory,sizeof(directory) - 1, "/files/");
for(i=0;i<strlen(directory);i++){
fname[i] = directory[i];
}
puts(fname);
fname[sizeof(fname) - 1] = '\0';
The error is that you forgot to NUL terminate your string when filling
directoryTmp
(in C strings are array ofchar
that by convention ends at the firstchar
whose value is0
). Then, whenstrcat
try to appendfname
it begins by iterating overdirectoryTmp
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, andstrcat
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:
Or as mentioned by others, just use
strncpy
:Note that
strncpy
does not guarantee that the string will be NUL terminated, so we have to take care of that ourselves.