#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 ?
unsigned char *stole;The above statement declares
stoleas a pointer tounsigned charand contains garbage value, pointing to some random memory location.scanf("%s", stole);The above statement tries to store some string to memory pointed by
stolewhich is being used by another program (atleast not allocated to your program for use). So, whenscanfattempts to over-write this memory, you getseg-fault.Try to allocate memory to
stoleas followsunsigned char stole[MAX_SIZE];or
Dynamic String Input