-3

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.

  • FYI `\\` is a backslash, not a forward slash. – jarmod Sep 14 '21 at 13:20
  • 1
    Use a debugger - the DIY solution. – Paul Ogilvie Sep 14 '21 at 13:20
  • I'm pretty sure `name[-1-i]` and `addr[i]` will always go out of bounds. Do you expect a negative index to wrap around to the last index of the array or something? – mediocrevegetable1 Sep 14 '21 at 13:22
  • @mediocrevegetable1 `i` starts at -1 and decreases (gets more negative) so `-1-i` starts at 0 and gets more positive. – jarmod Sep 14 '21 at 13:24
  • You should not define name as static char with size of 100 but as char* and alloc number of char of input file name +1. Look at strrchr function. Loop from length of file name backward. Stop of loop should take into account \ char and you are still in the string. – Ptit Xav Sep 14 '21 at 13:25
  • The code `int i = -1; for (; addr[i] != '\\'; --i) ...` will try to access `addr[-1]`. If the loop continues with `--i`, it will access `addr[-2]` etc. All this is undefined behavior. If you call your program without an argument, `addr` will be a `NULL` pointer. In this case accessing `addr[i]` with any value `i` is undefined behavior. – Bodo Sep 14 '21 at 13:25
  • Or you could simply return a pointer to the first character of the name within argv[1] and not have to allocate *any* additional storage. – jarmod Sep 14 '21 at 13:25
  • @jarmod sorry, I didn't realize the `-` negates `i`'s `-`. Weird form of indexing though... I'm pretty sure `addr[i]` is still out of bounds though. – mediocrevegetable1 Sep 14 '21 at 13:27
  • " it just stalls for a few seconds, and exits. " --> `for (; addr[i] != '\\'; --i)` leads to access error when `addr[]` lacks a `'\\'` (or in this case the illegal accessed data befoe it). Loop fails to stop. – chux - Reinstate Monica Sep 14 '21 at 13:27
  • @mediocrevegetable1 Well, yes. Isn't a[-1](a being any array), just the last element of array a? And, `name[-1-i]` is supposed to increase from i upto the last element(which will have index number `-1-i`, when i reached the point where addr[-i] is a back-slash.) – Anuj Jodha Sep 14 '21 at 13:30
  • @AnujJodha yes, a[-1] is the last element of the array ... in Python. This is not Python. – jarmod Sep 14 '21 at 13:31
  • @AnujJodha no it isn't. In C, that means "Go one element behind the array" or `*(a - 1)`, which is undefined behavior. – mediocrevegetable1 Sep 14 '21 at 13:32
  • Please [edit] your question and explain what you mean with "*return file name from address*". Show some example input and the corresponding expected output. If you want the part of the string after the last backslash you could check the documentation of `strrchr`. – Bodo Sep 14 '21 at 13:34
  • What it a "file address"? Show input and expected output. – klutt Sep 14 '21 at 13:36
  • @klutt Input would be something like(for example), `"G:\folder1\folder2\abc.txt"`, and the expected output would be `"abc.txt"`. – Anuj Jodha Sep 14 '21 at 13:39
  • @AnujJodha Update the question with that info – klutt Sep 14 '21 at 13:40
  • Duplicate https://stackoverflow.com/questions/5901624/extract-file-name-from-full-path-in-c-using-msvs2005 – klutt Sep 14 '21 at 13:44
  • Does this answer your question? [How to extract a file name from a full path](https://stackoverflow.com/questions/5901624/how-to-extract-a-file-name-from-a-full-path) – TylerH Sep 14 '21 at 14:00

1 Answers1

3

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?

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Actually, I used addr[i] as the condition statement because of a page on geeksforgeeks: https://www.geeksforgeeks.org/c-tricks-competitive-programming-c-11/. According to point number 4, it should work. – Anuj Jodha Sep 14 '21 at 13:25
  • @AnujJodha That site has a very bad reputation. Learn programming from proper books and classes, not from trashy internet tutorials... And no, point number 4 doesn't say anything about using negative array indices. – Lundin Sep 14 '21 at 13:26
  • 1
    @AnujJodha the page you linked is for "C++ tricks for competitive programming (for C++ 11)", AKA not something you would generally want to write in normal, ideally readable code. Though the real issue is indexing out of bounds here. – mediocrevegetable1 Sep 14 '21 at 13:28
  • @Lundin Then, what should I use instead of "GeeksForGeeks"? – Anuj Jodha Sep 19 '21 at 10:51
  • @AnujJodha Read a book. – Lundin Sep 19 '21 at 16:02