CloudN9ne
CloudN9ne

Reputation: 235

Input too big for array

I have a small question that I was just wondering about.

#include <stdio.h>

int main()
{
    char n_string[5];

    printf("Please enter your first name: ");
    scanf("%s", n_string);
    printf("\nYour name is: %s", n_string);

    return 0;
}

On the 5th line I declare a string of 4 letters. Now this means I will only be able to hold 4 characters in that string, correct? If I execute my program and write the name: Alexander, I get the output:

Your name is Alexander.

My question is, how come I could put a string of 9 characters into an array that holds 4?

Upvotes: 2

Views: 612

Answers (4)

merlin2011
merlin2011

Reputation: 75585

You are overwriting a part of your program's stack by doing that, which is generally a very bad thing. In this case, you got lucky, but if you write further you will almost certainly get a segfault, when main tries to return.

Malicious actors will use this as a buffer overflow attack, to overwrite a function's return address.

If your question is "Why does C allow me to do this?", the answer is that C does not do bounds checking on arrays. It treats arrays (more or less) as a pointer to an address in memory, and scanf is more than happy to write to the memory location without worrying about what it actually represents.

Upvotes: 3

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29985

You allocated 5 bytes, but since your CPU probably requires 16-byte alignment, the compiler probably allocated 16 bytes. Try this :

char n_string[5];
volatile int some_int;

some_int= 0;
sscanf(..);

printf("%s %d\n", n_string, some_int);

Is some_int still 0? Writing into n_string may have caused a buffer overflow and written bad data to some_int. Of course your compiler probably knows that some_int will stay a zero, so we declare it like volatile int some_int; to stop it from optimizing.

Upvotes: 3

nvoigt
nvoigt

Reputation: 77324

You reserve memory for 4 letters and the terminating zero. You write nine letters and a zero to it. You overstepped your bounds by 5 bytes. Those 5 bytes belonged to someone else, you just trashed his memory.

The most likely candidate for this is variables that are close. Test this, although not guaranteed, chances are you will see what happens with your remaining bytes: they will damage your i variable:

#include <stdio.h>

int main()
{
    char n_string[5];
    int i = 17;

    printf("Please enter your first name: ");
    scanf("%s", n_string);
    printf("\nYour name is: %s", n_string);
    printf("\nThe variable i is %d", i);

    return 0;
}

Upvotes: 2

Martin Costello
Martin Costello

Reputation: 10872

I think there just happens to be valid memory in your process at the address contiguous to your array that means it just happens to work. However, it will be corrupting other memory elsewhere in the process by overwriting it.

Essentially you have a buffer overflow.

Upvotes: 1

Related Questions