Adnan Khan
Adnan Khan

Reputation: 665

Array limit doesn't work

I wrote this little program to practice arrays, which is supposed to take in a max of 10 characters, and the ending \0. It works, but it works too well, and even if I put in a 50 character name, it spits out the correct input. What gives?

#include <stdio.h>


int main(int argc, char const *argv[])
{
char name[11];

printf("Enter your name: ");
scanf("%s", name);

printf("Hi, %s\n", name);   
return 0;
}

Upvotes: 2

Views: 137

Answers (2)

Adrian Cornish
Adrian Cornish

Reputation: 23876

You are overwriting past the end of the array that you allocated - you need to specify as part of the scanf the length of the string to be read to make sure that it fits.

scanf("%10s", name);

An improvement to your code would be to generate the format string so that it always has the right size.

#include <stdio.h>


int main(int argc, char const *argv[])
{
char name[11];
char formatstr[50];

snprintf(formatstr, sizeof(formatstr), "%%%ds", sizeof(name)-1);

printf("Enter your name: ");
scanf(formatstr, name);

printf("Hi, %s\n", name);
return 0;
}

Upvotes: 8

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14595

When you allocate an array in C you are just getting the starting memory address of a block of memory guaranteed to be free for you to use, nothing more. This guarantee is based in the assumption that you are not going to use this array to read/write any memory location outside of its boundaries, which you just did!

Higher level languages, such as Java or C#, will throw an exception (an error) when you try to access a memory location outside of your array boundaries, unfortunately in C you are on your own.

Even though you example seems harmless, this kind of access violation is a common bug in software development and can lead from simple malfunctioning to an accidental stack-overflow!

Upvotes: 1

Related Questions