Why do I get segfault at the end of the application after everything is done correctly?

#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 works well, but with one problem - if the password is correct, then it prints "some stuf here ...", but also shows a segmentation error at the end. Why?

+3
source share
3 answers

unsigned char *stole;
The above statement declares stoleas a pointer to unsigned charand contains the value of the garbage, pointing to a random memory location.

scanf("%s", stole);
, stole, ( , ). , scanf , seg-fault.

stole

unsigned char stole[MAX_SIZE];

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

+4

stole - - (, malloc)

+1

stole, :

unsigned char stole[1024];

segfault, , 1024 , , , :

scanf("%1023s", stole);

1023 1024, .

+1

Source: https://habr.com/ru/post/1739591/


All Articles