visual c++ - VC++ read variable length char* -


i'm trying read variable length char* user input. want able specify length of string read when function called;

char *get_char(char *message, unsigned int size) {     bool correct = false;     char *value = (char*)calloc(size+1, sizeof(char));     cout << message;      while(!correct) {         int control = scanf_s("%s", value);         if (control == 1)             correct = true;         else             cout << "enter correct value!" <<endl                 << message;          while(cin.get() != '\n');     }      return value; } 

so, upon running program , trying enter string, memory access violation, figured has gone wrong when accessing allocated space. first idea went wrong because size of scanned char * not specified within scanf(), doesn't work correct length strings either. if give calloc size of 1000 , try enter 1 character, program crashes.

what did wrong?

you have specify size of value scanf_s:

int control = scanf_s("%s", value, size); 

does trick.

see documentation of scanf_s example of how use function:

unlike scanf , wscanf, scanf_s , wscanf_s require buffer size specified input parameters of type c, c, s, s, or [. the buffer size passed additional parameter following pointer buffer or variable.

i omit rest of msdn description here because in example they're providing, use scanf instead of scanf_s quite irritating...


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -