简体   繁体   中英

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:

#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] ; to char catfish[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" . That string is 9 characters long, which means you need a size-10 buffer to store the null-terminator.

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). 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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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