Stephane B. Stephane B. - 4 months ago 25
C Question

C - strtok_s - Access violation reading location

I can't understand why I get the following message for my function below (in Visual Studio 2015).

0xC0000005: Access violation reading location 0x0000002C.

I have read this answer but it does not help me.

What this code is about.

There is a string of ints separated in groups of "index,value" pairs. Indexes are unique. Each group is separated by a semi-colon. Example: 1,2;3,5;2,2;3,4

I am trying to get an array of int with each value at its index.

My code so far extracts the strings and puts it into a
char* buffer

Then I separate the groups of "index,value" by the semi-colons and store them in
char** arrayKeyValue
, which is a member of
struct inputElement
. The other struc member is a int representing the number of "index,value" groups in the array. I do this with the function "separateStringBySemicolon".

Then I try to separate each group of "index,value" into a new array, where at each "index" will match its "value". I do this by passing my struct to the function "separateKeyValue". I use
but I get an error.

The first call to the function below (
token2 = strtok_s(arrayOfKeyValue[j], sepComma, &next_token2);
) brings the error. I understand that
cannot be accessed, but I am not sure. And if so, why?

double* separateKeyValue(struct inputElement* inputElement)
int count = inputElement->length;
char** arrayOfKeyValue = inputElement->data;

double* arrayDecimal = malloc(count * sizeof(double));
char sepComma = ','; //wrong should be char sepComma[] = ",";
char* token2 = NULL;
char* next_token2;

printf("Value in arrayofkeyvalue: %s", arrayOfKeyValue[0]);

for (size_t j = 0; j < count; j++)
token2 = strtok_s(arrayOfKeyValue[j], sepComma, &next_token2);
unsigned int index;
sscanf_s(token2, "%d", &index);

double value;
sscanf_s(next_token2, "%d", &value);

arrayDecimal[index] = value;

printf("res[%d] = %d\n", index, arrayDecimal[index]);

return arrayDecimal;


You are specifying a char constant, sepComma, as the second parameter to strtok_s, where it expects a string of delimiter characters.

(not so) Coincidentally, the ASCII value of ',' is 0x2C.