C - strtok_s - Access violation reading location

-1

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 strtok_s 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 token2 or next_token2 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]);
        printf("\n");
    }

    return arrayDecimal;
}
c
asked on Stack Overflow Nov 21, 2016 by Stephane B. • edited May 23, 2017 by Community

1 Answer

1

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.

answered on Stack Overflow Nov 21, 2016 by Michael Foukarakis

User contributions licensed under CC BY-SA 3.0