wikarus wikarus - 1 year ago 111
C Question

Run-Time Check Failure #2 - Stack around the variable was corrupted

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);

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... :(

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download