views:

73

answers:

3
#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 password is correct then it DOES do the printing of 'some stuf here...' but it also shows me segmentation fault error at the end. Why ?

+1  A: 

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

Paul R
I don't see any need to use `malloc` here - I'd just say `unsigned char stole[SOMESIE];` where `SOMESIZE` is an appropriate size.
anon
@Neil: sure, that's why I said *e.g.* - it's just one way to allocate some memory - a static allocation is also good.
Paul R
A: 

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.

Andreas Brinck
Tnx for knowing the fix with scanf - i've never seen it before!
VaioIsBorn
@VaiolsBorn You're welcome ;)
Andreas Brinck
+4  A: 

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

N 1.1