Question

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';
Was it helpful?

Solution 2

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.

OTHER TIPS

chars are put in single quotation marks (''), not double (""). You're assigning string literals to each array index.

You can simply do like this

char fname[255];
char directoryTmp[262];

/*Working Code for entering the filename fname with fgets() */
...

/* specify the directory */ 
strcpy(directoryTmp,"/files/");


/* 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]; //You need to take care here. Because size of the fname is 255 and size of the directoryTmp is 262. you should check length of the fname in for loop.  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top