I've already saw some questions here at stackoverflow but none of them has solved my problem...
i have that code in C:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char str[] = "";
scanf("%[^\n]", str);
printf("Você digitou: %s\n", str);
system("pause");
}
When i run the program, i had the error:
Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.
now, i really don't know what i'm doing wrong there... :(
You should not overwrite a constant with user input. Replace char str[] = ""
with char * str = malloc(<enough bytes for any possible input)
or even learn about safer APIs.
The array str
can only hold a single char
given its initialisation. The call to scanf()
will be overwriting the bounds the str
causing undefined behaviour, in this case corrupting the stack. You need to decide how large the str
array should be and limit the number of characters read to prevent buffer overrun.
To use scanf()
you specify the maximum number of characters to read:
char str[1024];
if (1 == scanf("%1023[^\n]", str)) /* Check return value to ensure */
{ /* 'str' populated. */
} /* Specify one less than 'str' */
/* size to leave space for null.*/
You could also use fgets()
but would need to remove the new-line character afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With