问题
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
回答1:
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.
回答2:
Yes, you got an error. And the most unfortunate part is that you don't know about it. You might know about it later on in the program when something mysteriously crashes (if you're lucky), or when your client's lawyers come to sue you (if you're not).
来源:https://stackoverflow.com/questions/5100210/how-to-use-calloc-in-c