Varun Dalal
Varun Dalal

Reputation: 39

Why does my debugger show extra characters in character array?

Notice the input string value shown:

debugger screenshot

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?

Upvotes: 2

Views: 244

Answers (3)

Fiddling Bits
Fiddling Bits

Reputation: 8861

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

Upvotes: 2

Majkl
Majkl

Reputation: 153

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.

Upvotes: 1

sagi
sagi

Reputation: 40491

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

Upvotes: 1

Related Questions