i'm trying to make a simple function that returns a string in a secure way, and i would like to know what's wrong with this code.
i decided to use read because both scanf and fgets gave e troubles,
specifically, scanf gives me abort trap 6 if i overflow the buffer even with the lenght check obviously,
while fgets takes the input , returns the error message if the string i inserted was too long, but then preturn the string anyway without allowing me to reenter another string.
This is the code:
string get_string(const string prompt)
{
char temp[30];
int size,count;
printf("%s",prompt);
do
{
count=read(0,temp,29);
temp[count]='\0';
size=strlen(temp);
if(size>24)
{
printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
}
printf("size :%i\n",size);
}
while(size>24);
stripc(temp,'\n'); //removes new line
string word=malloc((size)*sizeof(char));
strcpy(word,temp);
return word;
}
Now with read it gives me kind of the same error, i read from stdin for a total of 30 bytes,
then i add null character at the end with the counter, but if the length exceeds this is the output:
ppppppppppppppppppppppppppppp
Error: too long.
size :30
size :2
p
Any idea what the problem is?
Is there another way to achieve what i need?
EDIT: The problem is not going out of range,
The strange thing is the fact that once i write more than 24 chars,
the function that should read input(read,scanf,fgets or whatever),
doesn't activate anymore, that's why size: appears two times in a row,
the input insertion is skipped for some reason and i would like to understand why.
i corrected some mistakes.