string - How to use calloc() in C? -


shouldn't error if string goes on 9 characters long in 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 word: ");     scanf("%s", astring);      printf("you typed in: %s\n", astring);     //printf("string length: %i\n", strlen(astring)); } 

thanks

blargman

you don't compiler error because syntax correct. incorrect logic and, undefined behavior because writing memory past end of buffer.

why undefined behavior? well, didn't allocate memory means doesn't belong -- intruding area closed off caution tape. consider if program using memory directly after buffer. have overwritten memory because overran buffer.

consider using size specifier this:

scanf("%9s", astring); 

so dont overrun buffer.


Comments

Popular posts from this blog

mod rewrite - Doing external redirect. .htaccess NS flag not working. How to achieve similar results? -

mysql - How to insert just year and month into date field? -