找到你要的答案

Q:Why does the stack get corrupted?

Q:为什么堆栈会损坏?

int compare_chars(const void* a, const void* b)
{
    char* c1 = (char*)a;
    char* c2 = (char*)b;

    return *c1 - *c2;
}

int main(int argc, char* argv)
{
    FILE* file = fopen("c:\\file.txt", "r");
    assert(file != NULL);

    char word[10] = { 0 };

    while (!feof(file))
    {
        fscanf(file, "%s", &word);

        qsort(word, 10, sizeof(char), &compare_chars);

        for (int i = 0; i < 10; i++)
            printf("%c", word[i]);
        printf("\n");
    }

    fclose(file);
}

I get the following message:

Run-Time Check Failure #2 - Stack around the variable 'word' was corrupted.

It happens on a valid file containing only "0123456789" (10 characters).

Why?

int compare_chars(const void* a, const void* b)
{
    char* c1 = (char*)a;
    char* c2 = (char*)b;

    return *c1 - *c2;
}

int main(int argc, char* argv)
{
    FILE* file = fopen("c:\\file.txt", "r");
    assert(file != NULL);

    字符字[ 10 ] = { 0 };

    while (!feof(file))
    {
        fscanf(file, "%s", &word);

        qsort(word, 10, sizeof(char), &compare_chars);

        for (int i = 0; i < 10; i++)
            printf("%c", word[i]);
        printf("\n");
    }

    fclose(file);
}

我得到以下信息:

Run-Time Check Failure #2 - Stack around the variable 'word' was corrupted.

它发生在一个有效的文件只包含“0123456789”(10个字符)。

为什么?

answer1: 回答1:

In fscanf statement-

  fscanf(file, "%s", &word);
                     ^not needed (remove &)

char word[10] = { 0 };

Strings are null terminated. So increase size of array word to include '\0'.

Also while (!feof(file)) is wrong .

EDIT

Instead you can control loop with fscanf-

while(fscanf(file, "%s", word)==1){
// your code
 }

Because upon successful completion, fscanf shall return the number of successfully matched and assigned input items.

Here in your case fscanf will return 1 on success.

在效用表—

  fscanf(file, "%s", &word);
                     ^not needed (remove &)

字符字[ 10 ] = { 0 };

字符串被终止。因此,增加数组字的大小,包括' 0 '。

同时也!外汇经营资金(文件))是错误的。

EDIT

相反,你可以控制回路与效用—

while(fscanf(file, "%s", word)==1){
// your code
 }

因为一旦成功完成,fscanf应当返还一些成功匹配和分配输入项。

在这里,你将成功fscanf返回1。

answer2: 回答2:

Strings in c are null-terminated, so you need to allocate space for the string terminator.

To fit a 10-character long word you need to allocate 11 bytes:

char word[11] = { 0 };

C中的字符串是空终止的,所以需要为字符串终止符分配空间。

为了适应10字长的字,你需要分配11字节:

char word[11] = { 0 };
answer3: 回答3:

A 10-character string takes 11 chars to represent (1 extra for the null byte at at the end).

一个10个字符的字符串以11个字符来表示(1额外的零字节在最后)。

c