开发者

Why do i get segfault at the end of the application after everything's been done properly?

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
        unsigned char *stole;
        unsigned char pass[] = "m4ak47";
        printf("Vnesi password: \t");
        scanf("%s", stole);
        if(strncmp(stole, pass, sizeof(pass)) != 0)
        {
                printf("wrong password!\n");
                exit(0);
        }
        else
                printf("Password correct\n");
        printf("some stuf here...\n\n");
        return 0;
}

This program is working nice, but with one problem - if the pass开发者_开发技巧word is correct then it DOES do the printing of 'some stuf here...' but it also shows me segmentation fault error at the end. Why ?


unsigned char *stole;
The above statement declares stole as a pointer to unsigned char and contains garbage value, pointing to some random memory location.

scanf("%s", stole);
The above statement tries to store some string to memory pointed by stole which is being used by another program (atleast not allocated to your program for use). So, when scanf attempts to over-write this memory, you get seg-fault.

Try to allocate memory to stole as follows

unsigned char stole[MAX_SIZE];

or

unsigned char *stole = malloc((MAX_SIZE+1) * sizeof(char));
// +1 for null-terminating

Dynamic String Input


stole is a dangling pointer - you need to allocate some memory for it (e.g. malloc)


You have to supply the storage for stole, something like:

unsigned char stole[1024];

This will still give a segfault if the user enters a longer string than 1024 chars though, to fix this you can use:

scanf("%1023s", stole);

1023 is used instead of 1024 so that there's room for the string terminator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜