1

I have a piece of code that works fine on char[] but gives a run-time error when performed on a char*.

#include <stdio.h>
#include <string.h>

void rotateLeft(char* str, int pos, int size){
    char temp;
    int i;
    for(i=pos; i < size-1; i++) {
        temp = str[i];
        str[i] = str[i+1];
    }
    str[size-1] = temp;
}

void removeAllDups(char* str) {
    int size = strlen(str);
    int i,j;
    char cur;
    for (i=0; i<size; i++) {
        cur = str[i];
        for(j=i+1; j<size;) {
            if (str[j] == cur) {
                rotateLeft(str, j, size);
                size--;
                str[size] = '\0';
            }
            else {
                j++;
            }
        }
    }
}


int main(void) {
    char str1[] = "hello there";
    char* str2 = malloc(sizeof(char)*14);
    strcpy (str2, "goodbye matey");
    removeAllDups(str1); // succeeds
    printf("%s\n", str1);
    removeAllDups(str2); // fails
    printf("%s\n", str2);
    free(str2);
    return 0;
}

Run-time error is given when removeAllDups(str2) is reached. What is my problem?

richizy
  • 2,002
  • 3
  • 21
  • 26

2 Answers2

2

char* str2 = "goodbye matey" is equivalent to declaring static const char str2[] = "goodbye matey". So you cannot modify the content pointed to by str2.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
2

char* str2 = "goodbye matey"; initializes str2 with a pointer to data that should not be changed. While str2 points to such data, modiying it leads to UB.

char str1[] = "hello there";
char* str2 = "goodbye matey";
removeAllDups(str2); // fails
str2 = str1;
removeAllDups(str2); // OK
str2 = "goodbye matey2";
removeAllDups(str2); // fails
str2 = strdup("goodbye matey3");
removeAllDups(str2); // OK
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256