Reputation: 175
i have this run time error "access violation writing location " with strcpy function
Here part of my code:
else if (strcmp(sentenceRecv, "405002") == 0){
/*winVersion[SIZE] = (char*)malloc(sizeof(tempString));*/
system("ver >> text.txt");
FILE *pfile = fopen("text.txt", "rt+");
if (pfile == NULL)
{
printf("Couldn't open file\n");
}
fread(tempString, sizeof(char), SIZE - 1, pfile);
fclose(pfile);
pfile = fopen("text.txt", "w");
if (pfile == NULL)
{
printf("Couldn't open file\n");
}
fputc((int)' ', pfile);
fclose(pfile);
/* winVersion[SIZE] = strdup(tempString);*/
strcpy(winVersion, tempString);
send(ClientSocket, winVersion, sizeof(winVersion), 0);
menuCheck = 1;
}
The error is in this line:strcpy(winVersion, tempString);
and in the first lines i write:
char winVersion[SIZE];
char tempString[SIZE];
Upvotes: 0
Views: 932
Reputation: 868
char tempString[SIZE] = {0};
strcpy() needs a null-terminated string ('\0')
Otherwise it will just keep going until it hits a '\0' somewhere in the contiguous memory which may not belong to your program hence the access violation error.
You could use char *strncpy(char *dest, char *src, size_t n);
and specify SIZE as the n number of bytes to copy. This is still somewhat unsafe because the copied strings won't be null-terminated either and could cause more problems later.
http://beej.us/guide/bgc/output/html/multipage/strcpy.html
Upvotes: 2