0

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!

4
  • Please provide complete code as a minimal reproducible example. For example, we do not know what string you are passing to the function. But for starters, consider what value last_slash will be if there is no / character in the string. Commented Feb 19, 2022 at 11:15
  • 3
    (*url++) if (*url you are omitting first character. You have to increment after checking. Commented Feb 19, 2022 at 11:16
  • 2
    Also, lastslash is never initialized, and contains random bits. If you never find a '/', you will write your '\0' wildly somewhere in to memory. Commented Feb 19, 2022 at 11:22
  • regarding: (*url++) This has a precedence problem. Suggest: ( (*url)++) so the target variable is incremented rather than the url pointer. Commented Feb 20, 2022 at 18:05

1 Answer 1

1

Initialize last_slash so that you can properly check if a '/' was found after the loop. Restructure the loop to only move the pointer after first checking the value it points to.

#include <stdio.h>

void remove_filename(char *url)
{
  char *last_slash = NULL;

  for (; *url; url++)
      if (*url == '/')
          last_slash = url;

  if (last_slash)
      *last_slash = '\0';
}

int main(void)
{
    char buffer[] = "path/to/some/file.data";

    printf("<<%s>> -> ", buffer);
    remove_filename(buffer);
    printf("<<%s>>\n", buffer);
}

Output:

<<path/to/some/file.data>> -> <<path/to/some>>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.