sid_mac
sid_mac

Reputation: 341

C - How to Allocate Memory to string input with variable length?

I have a simple error that I know lies underneath my C code's memory usage, because the iterator in a simple for loop changes drastically after receiving user input on the command line:

int i = 1;
char input[] = "";
for (i = 1; i <= 5; i++) {
    printf("i  %d\n> ", i);
    scanf("%s", input);
    printf("input %s\ni %d\n", input, i);
}

The output should be simple enough:

i 1
> <receive input>
input <input>
i 1

to be repeated 5 times.

However, the iterator 'i' changes to anything but what is expected when any input is received.

An example output:

i  1
> 45
input 45
i 53

I have a hunch that this comes from memory access in the compiler. Anything helps!

Upvotes: 1

Views: 291

Answers (2)

Jeroen3
Jeroen3

Reputation: 935

scanf("%s", input);

From the docs of scanf:

%s Matches a sequence of bytes that are not white-space characters. The application shall ensure that the corresponding argument is a pointer to the initial byte of an array of char, signed char, or unsigned char large enough to accept the sequence and a terminating null character code, which shall be added automatically.

You are the application. char input[] = ""; is only 1 byte big.
Any character returned by the scanf will result in overflowing input due to the null terminator. And will write over the next variable in memory.

Try:

char input[100] = "";
scanf("%100s", input);

Upvotes: 2

Caleb
Caleb

Reputation: 124997

Look at how your local variables are declared:

int i = 1;
char input[] = "";

input is a zero-length string, and there's no room allocated for the input you're about to ask for. When you do:

scanf("%s", input);

the input gets written into the array pointed to by input, but since there was no space reserved for that, whatever happens to be after the array that input refers to gets written over. In this case, that's I.

To solve the problem, you need to make sure that there's enough room for the input at the location where you're putting it. Also, you should limit the allowable length of the input so that the user can't enter more data than the size of the space you've reserved.

Upvotes: 2

Related Questions