简体   繁体   中英

Why does my debugger show extra characters in character array?

Notice the input string value shown:

调试器截图

I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define MAX 50
int main()
{
    printf("\nEnter string:");
    char input[MAX];
    gets(input);
    puts(input);
    return 0;
}

I entered "(A+B)*C" as input. But why does the debugger show extra characters?

Shouldn't it be just \0 at the end?

A string in C is terminated by the NUL character: '\0' . You can ignore all characters after this in your array, input , as they are uninitialized/garbage.

You can, though it's unnecessary in your case, initialize your array before using it:

char input[MAX] = {'\0'};

This way you'll see all '\0' s after "(A+B)*C" .

This is called Garbage data that is stored on the address that your buffer got, and was not used. You can simply make it go away by adding a null terminator '\n'.

I would recommend using fgets() instead of gets() because gets() can be dangerous (In order to use gets() safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough). fgets() also takes the '\n' char at the end, in order to prevent this you can write the following line: input[strlen(input)-1] = '\0';

As for your question @Fiddling Bits already provided correct answer.

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