how to use crypt( ) method in Linux?

user1198331 picture user1198331 · Mar 21, 2013 · Viewed 24.5k times · Source

I just want to use crypt() to generate an encrypted password,and I write a demo which invoke the crypt() method. Here is my code

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%s\n",crypt("abc","ab"));
    exit(0);
}

I compile it using "gcc tem.c -lcrypt' and when I run it, everything seems right, but a "segment error" shows up. so please tell me what's wrong with this simple program?

Answer

Some programmer dude picture Some programmer dude · Mar 21, 2013

If you compile with the flag -Wall you will see why.

If you read the manual page you will see that it uses #define _XOPEN_SOURCE before including <unistd.h>. It should actually be defined before including any header.

If you don't define _XOPEN_SOURCE then the crypt function will not be prototyped. Then the compiler doesn't know what the actual return type is, or the types and number of arguments. So it will assume that the function returns an int and your printf expects a string, so there will be a type mismatch that causes the crash.