[英]Segmentation fault when calling crypt function in C
I pass the argument Arturo $1$salt$ and I get a Segmentation fault (core dumped) error. 我传递了Arturo $ 1 $ salt $的参数,并且遇到了Segmentation Fault(核心转储)错误。
#define _XOPEN_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main (int argc, char* argv[])
{
if ( argc != 3) {
printf ("Usage: ./crypt key salt\n");
return 1;
}
printf ("%s\n", crypt (argv[1], argv[2]));
return 0;
}
The answer turned out to be simple - bash variable expansion. 答案很简单-bash变量扩展。 the
$
character is reserved in the shell, to mark the beginning of a variable $
字符保留在外壳程序中,以标记变量的开头
so when you run 所以当你跑步
./program Arturo $1$salt$
the argv[2]
after variable expansion will be 变量展开后的
argv[2]
将是
"$"
which is not a valid salt after the glibc specification (which expects $id$salt$
). 这不是glibc规范之后的有效盐(期望
$id$salt$
)。 The call to crypt
with that seed will return NULL
and set errno
to EINVAL
, because the seed is invalid, and the call to printf
chokes on the NULL
and segfaults, which is the behaviour you are seeing. 用该种子对
crypt
的调用将返回NULL
并将errno
为EINVAL
,因为该种子无效,并且对NULL
和segfaults的printf
的调用会阻塞,这就是您所看到的行为。
if you were to execute your program as follows, disabling variable expansion in the shell: 如果要按以下方式执行程序,请在外壳中禁用变量扩展:
./program Arturo '$1$salt$'
the output would be 输出将是
$1$salt$y5SOwLketmwNfSvW0yAoz/
as expected. 如预期的那样。
Assuming: 假设:
typedef char *string;
From crypt
POSIX documentation : 从
crypt
POSIX 文档中 :
The salt argument shall be a string of at least two bytes in length not including the null character chosen from the set:
salt参数应为长度至少为两个字节的字符串,其中不包括从集合中选择的空字符:
abcdefghijklmnopqrstu vwxyz ABCDEFGHIJKLMNOPQRSTU VWXYZ 0 1 2 3 4 5 6 7 8 9 .
abcdefghijklmnopqrstu vwxyz ABCDEFGHIJKLMNOPQRSTU VWXYZ 0 1 2 3 4 5 6 7 8 9。 /
/
but you pass $1$salt$
. 但您通过了
$1$salt$
。
So you have to check the return value of crypt
and print only if is ! = NULL
因此,您必须检查
crypt
的返回值并仅在is是的情况下打印! = NULL
! = NULL
. ! = NULL
。
Now, if you want to use crypt
function from glibc, you have to include crypt.h
header in your program. 现在,如果要使用glibc中的
crypt
函数,则必须在程序中包含crypt.h
标头。 See example in glibc documentation . 请参阅glibc 文档中的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.