I’m creating a program to open .txt files in a given directory, I have an array with all the absolute paths of the files inside the directory in question and I’m creating a function to extract and return the name of the files, the function is written as follows:
char *name(char *string) {
int i = strlen(string);
char *aux;
while(string[i-1] != '/'){
i--;
}
strcpy(aux, &string[i]);
return aux;
}
The above function is giving a Segmentation Fault error, but if I add the following line ” int j = 0;” before the declaration of aux the mistake is gone, the new and working code is
char *name(char *string) {
int i = strlen(string);
int j = 0;
char *aux;
while(string[i-1] != '/'){
i--;
}
strcpy(aux, &string[i]);
return aux;
}
input: C:\test\a.txt
output: a.txt
Why the addition of “int j = 0;” solves the problem? I’m stuck with that and can’t continue because I don’t know if this inconsistency might lead to bigger problems later, I’m thinking about writing my own function to copy the strings, but before that I really want to understand that error.
You never allocate
aux.auxneeds to point to a valid memory location before you attempt to copy anything to it.Instead of
char *aux, you need something likechar *aux = malloc(i+1);. Note thati+1is overkill because in your caseauxwill always be at least 3 characters shorter thanstring(it won’t containC:\), but you probably don’t care for such small strings. Remember tofree()the pointer once you’re done with it.Also, the reason you found it works by switching orders of declarations and/or adding a declaration is probably that you got lucky and somehow the location to which
auxpoints to is valid (if you do justchar *aux;,auxpoints to a random location). This is pure luck however, and is still invalid code even though it seems to work.In the future, you might want to use a tool like Valgrind to help you diagnose memory problems. You should also read a tutorial on basic memory management and pointers in C.