1

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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
ChasetopherB
  • 466
  • 9
  • 23

1 Answers1

3

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.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Nikita
  • 6,270
  • 2
  • 24
  • 37
  • 1
    In C++ it would not compile. – too honest for this site Sep 19 '16 at 22:57
  • Thing is, for the function that this code snippet exists in, the input string comes in as a string literal parameter. So I would need to find a way to copy the literal into an array, with the added bonus that I am not allowed to use string library functions. I am open to suggestions on that front. – ChasetopherB Sep 19 '16 at 23:45
  • @ChasetopherB Iterate over the string to get it's length. Allocate memory `char* modStr = malloc(strLen + 1)`. And copy the string content with `memcpy`. – Nikita Sep 20 '16 at 05:49