I'm working my way through C Programming: A Modern Approach but I'm having a bit of trouble with the last exercise of the chapter on strings.
I'm trying to replace a character in a string with a null character to remove the file_name but I keep getting a bus error and I don't understand what I am doing wrong:
void remove_filename(char *url)
{
char *last_slash;
while (*url++)
if (*url == '/')
last_slash = url;
*last_slash = '\0';
}
The way I see it, I am keeping track of the address of the last slash (in the last_slash pointer). Then I target the object stored at that address and replace it by a null character.
Any feedback as to why my reasoning is false is greatly appreciated!
last_slashwill be if there is no/character in the string.(*url++) if (*urlyou are omitting first character. You have to increment after checking.lastslashis never initialized, and contains random bits. If you never find a '/', you will write your '\0' wildly somewhere in to memory.(*url++)This has a precedence problem. Suggest:( (*url)++)so the target variable is incremented rather than theurlpointer.