简体   繁体   中英

Strcat() throws acces violation exception. Why?

int verify(char filename[], int filenameLength) // If f.ex. filename is "x.txt" then filenameLength is 5
{
    char* filenameCorrect = malloc(sizeof(char) * (filenameLength + 9));
    filenameCorrect = "correct_";
    strcat(filenameCorrect, filename);

    ...
}

Everytime i run this i get this exception: "Access violation writing location".

filenameCorrect is a pointer, not a variable that holds the characters rather a pointer to some area in memory that was assigned to hold the characters. In the second line you are reassigning filenameCorrect to point to a string that is compiled as part of the code and thus cannot be changed hence the error.

What you are looking for is to copy the string "correct_" to the allocated area in memory. So use:

strcpy(filenameCorrect, "correct_");

then you can safely use strcat .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM