Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

like image 670
wikarus Avatar asked Oct 08 '12 15:10

wikarus


2 Answers

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.

like image 27
bmargulies Avatar answered Sep 18 '22 12:09

bmargulies


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.

like image 199
hmjd Avatar answered Sep 22 '22 12:09

hmjd