mariner
mariner

Reputation: 930

c++ bus error:10 while trying to parse and update string

#include<stdio.h>
#include<ctype.h>

int main() {

  char* start = "There are no";
  char* d = start;
  char* s = d;

  while (s) {
    char c = *s++;
    if (ispunct(c) || isspace(c)) {
      continue;
    }
    *d++ = c;
  }

  printf("%s\n", start);

}

I am new to c/c++ and trying to understand to manipulate strings. The above code scans through the string and skips punctuations and spaces and prints the string without any punctuations and spaces.

While I run it I get "Bus error: 10"

What am I doing wrong?

Upvotes: 0

Views: 153

Answers (2)

billz
billz

Reputation: 45460

start is string literal, it's implicitly const, modify it will invoke undefined behavior. try:

char start[] = "There are no";

or just use string:

std::string start("There are no");

Upvotes: 1

Alexander L. Belikoff
Alexander L. Belikoff

Reputation: 5721

You are checking for a wrong thing in the loop condition. You should check for *s. s is a pointer and it will hardly ever become 0 in your code. Ultimately, you step into an unmapped memory region which causes SIGBUS.

Upvotes: 1

Related Questions