I want to read an string/array from the terminal/keyboard and write it to an string variable.
That’s easy:
— snip —
printf("Please enter the string now ... n") ;
scanf("%s", str1)
— snip —
But I also want to be sure that the string/array is not bigger than a certain size. But my approach doesn’t work at al and the user can produce a buffer overflow.
— snip —
#include<stdio.h> #include<stdlib.h> #include<string.h>
#define MAX_STRG 10
int main ( int argc, char *argv[] ) {
char str1[MAX_STRG/2]="One", str2[MAX_STRG/2]="Two" ;
int pos = 0, check = 1 ;
size_t lenstr = 0 ;
/* get the string */
while(check==1){
printf("Please enter the first string now ... n") ;
scanf("%5s", str1) ;
printf("Please enter the second string now ... n") ;
scanf("%5s", str2) ;
/* string size in bytes*/
lenstr = sizeof(str1) + sizeof(str2) ;
printf("n string1 string2 position StrgLenn %st %st %dt %d nn", str1,
str2, pos, (int)lenstr) ;
if (lenstr<=MAX_STRG+1){
check = 0 ;
}
}`
— snip —
But my check is to late and the string will be already written to memory when I check. I thought giving the size with the scanf statement would do the check but no.
In general I would like to find a way how to enter a string within defined length boundaries and if the string is to large an error is produced
Thanks in advance
sake
sake is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.