I am trying to write a function which would return the file name of a file, from its file address. It simply copies each character of the address, starting from the termination charater, uptil the first forward-slash '\\'
, to a char array variable named name
. And then, it simply reverses the order of all the charater in the variable name
. I wrote a function called file_name()
, like this:
char* file_name(char* addr){
static char name[100];
char temp;
int i = -1;
for (; addr[i] != '\\'; --i){
name[-1-i] = addr[i]; // -1-i increases from 0 as i decreases. We get the reversed name of the file in "name"
}
int len = -i; //array length is simply -i. we know that through as i acts as the counter in the above iteration.
for (int count = 0; count < len; count){
temp = name[count];
name[count] = name[len - 1 - count];
name[len - 1 - count] = temp;
}
return name;
}
I have declared name
as a static variable, after receiving a warning from the compiler, and looking it up on Google. I found that without declaring it with the static
keyword(or through dynamic allocation), name
is treated as a local variable, and being an array, gets 'deleted' after the return statement(I would like to know a proper explanation. I still kinda don't understand what that is. Only have a vague idea).
Now, this compiles just fine, after adding the main
function to the code:
int main(int argc, char** argv){
char* name = file_name(argv[1]);
printf("File name is: %s", name);
return 0;
}
Now, for some reason, I get no output. I give the executable a parameter with a valid file address, but it gives no output. On top of that, it just stalls for a few seconds, and exits. What's going on? I don't think it's a problem with the algorithm. The function has no problem returning arrays, as it works well in a simpler case. Why is it not working?
I am working on Windows 10 with the GNU compiler collection.
P.S. - I would be grateful to know if there is already a function in the standard library which returns file name from address. But nonetheless, would still want to know why my code isn't working.
CodePudding user response:
Here's one very obvious bug that can cause a crash:
int i = -1;
for (; addr[i]
Similarly -1-i
is wrong. Both of these are out-of-bounds undefined behavior bugs.
int len = -i;
is also wrong. You can't have negative array indices in C programming. See C17 6.5.6/8 for the formal source.
array, gets 'deleted' after the return statement(I would like to know a proper explanation
This very common beginner bug is mentioned in any half-decent C book. The SO canonical FAQ post about it is this one: Can a local variable's memory be accessed outside its scope?
The function has no problem returning arrays, as it works well in a simpler case.
If a function only works for some test cases, that's a very strong indication of the function not working well at all and just gave the correct results by (bad) luck in other cases. See What is undefined behavior and how does it work?