ChasetopherB ChasetopherB - 2 months ago 16
C Question

Segmentation fault in C when iterating through a string

I am very new to C and I am supposed to be creating the strtok function. Problem is, I keep getting a segmentation fault error in this code:

char *newstring = "testing, testing, tested."
while(*newstring != '\0' ){
/*replace delimiters with nulls*/
printf("STARTING ITERATION\n");
if(*newstring ==','){
*newstring='\0';
}

printf("newstring char in loop: %c\n", *newstring);
/*printf("delimiters char in loop: %c\n", *delimiters);*/
newstring++;
printf("END OF ITERATION\n");
}
printf("OUT OF ITERATION");


Output is thus:

STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop:
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop:
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: .
END OF ITERATION
Segmentation fault (core dumped)


So, it looks like it gets all the way through to the end of the string and the very end of the loop, but doesn't actually make it OUT of the loop. I am not sure what I am missing.

Answer

You're trying to modify a string literal, which is not allowed in C. If you change char *newstring = "testing, testing, tested." to char newstring[] = "testing, testing, tested.", then you are modifying the contents of the array.

Comments