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?