0

I am trying to write a program from removing spaces in a string in C. I tried to debug using gdb but I guess I am not very knowledgable in using that tool. My code is as follows:

#include<stdio.h>

void RemoveSpaces(char * str){
    char *var1, *var2;
    var1 =  str; var2 = str;
    while(*var1 != '\0'){
        if(*var1 != ' '){
            *var2 = *var1;
            var2++;
        }
        var1++;
    }
    *var2 = '\0';
}

int main(){
    char *str = "abc de";
    printf("Before: %s\n", str);
    RemoveSpaces(str);
    printf("After: %s\n", str);
    return 0;
}

I tried to set watch on var1 and var2 but I get SIGSEGV on line where *var2 = *var1; I looked for some code here before writing my own. Of course, the answer states that its untested but I am doing a similar statement on the line where I get error. Why wouldn't (thereotically) *i = *j++; give an error while *var2 = *var1; would? (I don't want someone to remove my error. I just want to know why I might be getting this error so that I can avoid it in future. )

Community
  • 1
  • 1
Pervy Sage
  • 841
  • 1
  • 10
  • 22
  • 3
    Yeah, because you are trying to modify a string constant in-place. (it's not an accident it's a **constant.**) If you initialize an array with it instead (`char str[] = "abc de";`), it will work. But there are a lot of duplicates of this very same problem already. – The Paramagnetic Croissant Aug 12 '14 at 04:52

1 Answers1

1

You can't modify a string literal - change:

char *str = "abc de";

to:

char str[] = "abc de";
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • If someone is curious as to what difference does `char str[]` makes, please visit: http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Pervy Sage Aug 12 '14 at 05:04