简体   繁体   English

C 程序产生奇怪的输出

[英]C program produces weird output

During my process of Learning CI decided to create a struct that gives me the size of fish I provide in it, my question is why when I write this small piece of code:在我学习 CI 的过程中,我决定创建一个结构体,该结构体给出了我在其中提供的鱼的大小,我的问题是为什么当我编写这段代码时:

#include <stdio.h>
#include <string.h>

struct fish
    {
        char catfish[9]; //reserve memory for 9 chars
        char goldfish[10]; //reserve memory for 10 chars
        char mackrel;
        char oldfish;
    };

int main()
{
    struct fish typeof_fish;

    strcpy(typeof_fish.catfish, "Big Fish\n");
    strcpy(typeof_fish.goldfish, "Small Fish\n");
    printf("%s\n", typeof_fish.catfish);

    return 0;


}

the output produces "Big Fish Small Fish" Output here输出产生“大鱼小鱼”输出在这里

yet when I rewrite the top piece of code and change char catfish[9] ;然而,当我重写最上面的一段代码并更改 char catfish[9] 时 to char catfish[10] :烧焦鲶鱼[10]

#include <stdio.h>
#include <string.h>

struct fish
    {
        char catfish[10]; //reserve memory for 10 chars
        char goldfish[10]; //reserve memory for 10 chars
        char mackrel;
        char oldfish;
    };

int main()
{
    struct fish typeof_fish;

    strcpy(typeof_fish.catfish, "Big Fish\n");
    strcpy(typeof_fish.goldfish, "Small Fish\n");
    printf("%s\n", typeof_fish.catfish);

    return 0;


}

it produces "Big Fish" output here在这里产生“大鱼”输出

thank you in advance for an answer on this puzzling bug提前感谢您对这个令人费解的错误的回答

You aren't leaving enough room for a null terminator in catfish[9] when you strcpy "Big Fish\\n" .当您 strcpy "Big Fish\\n"时,您没有为catfish[9]的空终止符留出足够的空间。 That string is 9 characters long, which means you need a size-10 buffer to store the null-terminator.该字符串有 9 个字符长,这意味着您需要一个大小为 10 的缓冲区来存储空终止符。

If a string misses the null terminator the output has undefined behaviour since the program has no way to know where the string ends.如果字符串错过了空终止符,则输出具有未定义的行为,因为程序无法知道字符串在哪里结束。

When you perform the first copy, strcpy() copies in total 10 bytes (9 from the string itself plus the terminator).当您执行第一次复制时, strcpy()总共复制 10 个字节(来自字符串本身的 9 个字节加上终止符)。 As you have allocated only 9 bytes in catfish , the terminator goes into the first byte of goldfish , which then gets overwritten when you copy the second string.由于您在catfish只分配了 9 个字节,因此终止符进入goldfish的第一个字节,然后在您复制第二个字符串时被覆盖。 Hence, when you do a printf() of catfish , it doesn't stop at the end of catfish but keeps printing until it finds the terminator at the end of goldfish .因此,当您执行catfishprintf()时,它不会在catfish的末尾停止,而是继续打印,直到在goldfish的末尾找到终止符。

In the second case you add enough space for the terminator not to be overwritten so when you print it will just print the contents of catfish as expected.在第二种情况下,您为终止符添加了足够的空间,以免被覆盖,因此当您打印时,它只会按预期打印catfish的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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