运行时错误"访问违规写入位置"具有strcpy功能

时间:2014-08-12 20:09:35

标签: c runtime-error strcpy

我有这个运行时错误“访问违规写入位置”与strcpy函数

这是我的部分代码:

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;
}

错误在这一行:strcpy(winVersion, tempString); 在我写的第一行:

char winVersion[SIZE];
char tempString[SIZE];

1 个答案:

答案 0 :(得分:2)

char tempString [SIZE] = {0};

strcpy()需要以空字符结尾的字符串(' \ 0')

否则它将一直持续到它击中' \ 0'在连续内存中可能不属于您的程序的某处,因此访问冲突错误。

您可以使用char *strncpy(char *dest, char *src, size_t n);并指定SIZE作为要复制的n个字节数。这仍然有些不安全,因为复制的字符串也不会被空终止,并且可能会在以后引起更多问题。

http://beej.us/guide/bgc/output/html/multipage/strcpy.html

相关问题