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… 🙁
The array
strcan only hold a singlechargiven its initialisation. The call toscanf()will be overwriting the bounds thestrcausing undefined behaviour, in this case corrupting the stack. You need to decide how large thestrarray 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:You could also use
fgets()but would need to remove the new-line character afterwards.