strtok causing segfault but not when step through code
I am new to C and I am trying to split a date/time string into separate variables. However, when I step through the code in gdb line by line, it works, however, when I let it run through normally without breakpoints it seg faults and I can't see why.
Below is the code:
char * dateTimeString = "2011/04/16 00:00";
char dateVar[11];
char timeVar[6];
if (splitTimeAndDateString(dateVar, timeVar, dateTimeString))
{
exit(1);
}
printf("Date: %s\tTime: %s\n", dateVar, timeVar);
Below is the function
int splitTimeAndDateString(char date[11], char time[6], char * dateString)
{
char *token;
token = strtok(dateString, " ");
int i = 0;
while (token != NULL)
{
if (i == 0)
{
strcpy(date, token);
}
else if (i == 1)
{
strcpy(time, token);
}
else
{
printf("Overrun date time string\n");
return 1;
}
token = strtok(NULL, " ");
i++;
}
return 0;
}
Thanks for any help you can provide.
The strtok()
function modifies string that you wants to parse, and replace all delimiters with \0
nul symbol.
Read: char * strtok ( char * str, const char * delimiters );
str
C string to truncate.
Notice that the contents of this string are modified and broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
In your code:
strtok(dateString, " ");
^
| is a constant string literal
dateString
points to "2011/04/16 00:00"
a constant string literal, and by using strtok()
your code trying to write on read-only memory - that is illegal and this caused segmentation fault.
Read this linked answer for diagram to understand: how strtok()
works?
Edit:
@: char * strtok ( char * str, const char * delimiters );
In given code example, str
is an array, not constant string literal. Its declaration:
char str[] ="- This, a sample string.";
Here str[]
is an nul terminated array of chars, that initialized with string and its length is equals to size of the assigned string. You can change the content of str[]
e.g. str[i] = 'A'
is a valid operation.
Whereas in your code:
char * dateTimeString = "2011/04/16 00:00";
dateTimeString
is pointer to string literal that is not modifiable e.g dateTimeString[i] = 'A'
is an illegal operation this time.