fseek()之后的奇怪行为已经奏效

yul*_*ian 1 c debugging fseek

我遇到了一种奇怪的行为.虽然调试,当while-loop循环的第一次:去后虽然/* "data-url" *//* "data-author" */部分代码我的下一个结果Debugging windows -> Watches:

(我正在使用Code :: Blocks IDE,Ubuntu 13.04)

长度dataUrl_tempString8个字节,长度dataAuthor_tempString11个字节,长度dataName_tempString9个字节......

第1张照片

但经过/* data-name */部分代码后,我得到的结果让我困惑:

第2张照片

现在它们的大小不是8,11和9字节!

有什么事?

你能帮我找到这种行为的原因吗?


这是该函数的代码:

int SubString_Search(char *fnameNew, char *strUrl, char *strAuthor, char *strName) {

    FILE *fp;
    FILE *ofp_erase;
    FILE *ofp;
    char ch_buf;
    int count = 0;

    char dataUrl[8] = "";
    char dataAuthor[11] = "";
    char dataName[9] = "";
    char *dataUrl_tempString = &dataUrl[0];
    char *dataAuthor_tempString = &dataAuthor[0];
    char *dataName_tempString = &dataName[0];


    if( (fp = fopen("output_temp.txt", "r")) == NULL) {
        printf("File could not be opened.\n");
        return (-1);
    }
    else {
        /* Erasing 'NEW' file if exists */
        ofp_erase = fopen(fnameNew, "w");
        fclose(ofp_erase);
    }



    ofp = fopen(fnameNew, "a");
    rewind(fp);

    while(!feof(fp)) {

        /* "data-url" */
        fread(dataUrl_tempString, 8, sizeof(char), fp);
        if(memcmp(dataUrl_tempString, strUrl) == 0) {
            fseek(fp, 2, SEEK_CUR);     // going up to required place to copy a string
            while( (ch_buf = getc(fp)) != '"') {
                fputc(ch_buf, ofp);
            }
            fputc('\n', ofp);
        }
        fseek(fp, -8, SEEK_CUR);


        /* "data-author" */
        fread(dataAuthor_tempString, 11, sizeof(char), fp);
        if(memcmp(dataAuthor_tempString, strAuthor) == 0) {
            fseek(fp, 2, SEEK_CUR);     // going up to required place to copy a string
            while( (ch_buf = getc(fp)) != '"') {
                fputc(ch_buf, ofp);
            }
            fputc(' ', ofp);
            fputc('-', ofp);
            fputc(' ', ofp);
        }
        fseek(fp, -11, SEEK_CUR);


        /* "data-name" */
        fread(dataName_tempString, 9, sizeof(char), fp);
        if(memcmp(dataName_tempString, strName) == 0) {
            fseek(fp, 2, SEEK_CUR);     // going up to required place to copy a string
            while( (ch_buf = getc(fp)) != '"') {
                fputc(ch_buf, ofp);
            }
            //fputc() not needed
        }
        fseek(fp, -8, SEEK_CUR); // jumping over 1 symbol from the beginning: `-8` instead of `-9`...


        count++;
        if(count == 5)
            break;
    }

    rewind(fp);
    fclose(fp);
    fclose(ofp);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Flo*_*ris 5

字符串需要有空间用于'\0'终止 - 您只为8个字符的字符串分配了8个字节(因此最少需要9个字节).根据内存中的内容,您将获得不可预测的结果.