Home > Back-end >  Difficulties when replacing char in string in C using pointers
Difficulties when replacing char in string in C using pointers

Time:02-20

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!

CodePudding user response:

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>>

CodePudding user response:

You are working with an uninitialized variable when your code don't find /

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

  last_slash = NULL;
  while (*url  )
    if (*url == '/')
      last_slash = url;

  if (last_slash != NULL)  
    *last_slash = '\0';
}
  •  Tags:  
  • c
  • Related