strtok giving Access violation writing location error in visual C

39 Views Asked by At

I am using and understanding strtok for a while but this time it is giving unexpected error. I can't figure out what's wrong. Please help. I am using Visual Studio on Windows 10.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char* filepath = "C:\\Users\\RAKESH\\source\\repos\\TESTING\\log.c";

    char* filename = strtok(filepath, "\\");

    while (filename != NULL)
    {
        filename = strtok(NULL, "\\");
    }

    printf("%s\n", filename);

    return 0;
}
1

There are 1 best solutions below

11
Rakesh Solanki On

Before I posted this question, I found the error intuitively. Actually strtok needs to manipulate the char array, so it needs read-write memory space in the char array to do so, so it can't work with string literals which are typically stored in read-only memory. So the solution is:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILENAME_MAX 260

int main(int argc, char* argv[])
{
    char* filepath = (char*)malloc(FILENAME_MAX * sizeof(char));
    
    strcpy(filepath, "C:\\Users\\RAKESH\\source\\repos\\TESTING\\log.c");

    char* filename = strtok(filepath, "\\");

    while (filename != NULL)
    {
        filename = strtok(NULL, "\\");
    }

    printf("%s\n", filename);
    free(filepath);
    return 0;
}

Note: This code does not give the filename but returns NULL as the filename, so to get the actual filename, the following code changes in the while loop are required:

while (filename != NULL)
{
    if (strstr(filename, ".") == NULL)
        filename = strtok(NULL, "\\");
    else
        break;
}