Shouldn't I get an error if my string goes over 9 characters long in this program?
// CString.c
// 2.22.11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char *aString = calloc(10, sizeof(char));
if (aString == NULL)
{
return 1;
}
printf("PLEASE ENTER A WORD: ");
scanf("%s", aString);
printf("YOU TYPED IN: %s\n", aString);
//printf("STRING LENGTH: %i\n", strlen(aString));
}
Thanks
blargman
You don't get a compiler error because the syntax is correct. What is incorrect is the logic and, what you get is undefined behavior because you are writing into memory past the end of the buffer.
Why is it undefined behavior? Well, you didn't allocate that memory which means it doesn't belong to you -- you are intruding into an area that is closed off with caution tape. Consider if your program is using the memory directly after the buffer. You have now overwritten that memory because you overran your buffer.
Consider using a size specifier like this:
scanf("%9s", aString);
so you dont overrun your buffer.