-6

Everything except for the main method was written by my professor, so supposedly it should work. For reference, I'm pretty sure this code is supposed to remove any repeating letters from a string, turning "blaahhhblah" into "blahblah". This code compiles with no errors or warnings (compiled under the 1999 standard) but gives a seg fault when I run it and I have no idea why. I feel like there's probably an obvious answer to this, but we don't use a book for this course and the professor hasn't taught very well so I'm lost.

void g(char* a) {
  char* b = a;
  while(*b) {
    while(*a == *b)
      b++;
    a++;
    a* = b*;
  }
}

int main() {
  char* x = "blaahhhblah";
  g(x);
}

2 Answers2

3

Problem is here.

a* = b*;  

Change this to a = b or *a = *b (depends on what you want to do, either pointer assignment or assignment of variables that pointer points to).

And

char* x = "blaahhhblah";  

should be

char x[] = "blaahhhblah";
haccks
  • 104,019
  • 25
  • 176
  • 264
1

g assumes that the string it is passed is a mutable string. Your compiler (like most) makes literal strings immutable. You are passing g a pointer to an immutable string. To fix this, you can use an array initialized with a literal, instead of a literal char*. So:

int main() {
  char x[] = "blaahhhblah";
  g(x);
}
Linuxios
  • 34,849
  • 13
  • 91
  • 116