Question

I can't figure out why the second while loop is not executing. It has an access violation on result[count] = atoi... I thought adding the strcpy would help because I realized the original string was being modified, but it made no difference. Also, I am using C++ actually, but most of the source is in C where speed is necessary.

int* split(const char* str, const char* delim)
{
    char* tok;
    int* result;
    int count = 0;

    char* oldstr = (char*)malloc(sizeof(str));
    strcpy(oldstr, str);

    tok = strtok((char*)str, delim);
    while (tok != NULL)
    {
        count++;
        tok = strtok(NULL, delim);
    }

    result = (int*)malloc(sizeof(int) * count);

    count = 0;
    tok = strtok((char*)oldstr, delim);
    while (tok != NULL)
    {
        result[count] = atoi(tok);
        count++;
        tok = strtok(NULL, delim);
    }
    return result;
}
Was it helpful?

Solution

    char* oldstr = (char*)malloc(sizeof(str));
    strcpy(oldstr, str);

You don't allocate enough space. Since str is a char *, you are allocating however many bytes a char * takes on your platform, which is probably not enough to hold a string. You want:

    char* oldstr = malloc(strlen(str)+1);
    strcpy(oldstr, str);

Or, for simplicity:

    char* oldstr = strdup(str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top