为什么 fclose 出现段错误?
我显然错过了一些东西。 有人可以解释一下为什么会发生这种情况吗?
#define RANDOM_DEVICE "/dev/random"
int create_shared_secret(char * secret,int size)
{
FILE * file=NULL;
int RetVal;
file=fopen(RANDOM_DEVICE,"r");
if(!file)
{
printf("Unable to open random device %s\n",RANDOM_DEVICE);
exit(-1);
}
RetVal=fread(&secret,1,size,file);
if(RetVal!=size)
{
printf("Problem getting seed value\n");
exit(-1);
}
if(file) fclose(file); //segfault right here
return 0;
}
I'm clearly missing something. Could someone please explain why this would happen?
#define RANDOM_DEVICE "/dev/random"
int create_shared_secret(char * secret,int size)
{
FILE * file=NULL;
int RetVal;
file=fopen(RANDOM_DEVICE,"r");
if(!file)
{
printf("Unable to open random device %s\n",RANDOM_DEVICE);
exit(-1);
}
RetVal=fread(&secret,1,size,file);
if(RetVal!=size)
{
printf("Problem getting seed value\n");
exit(-1);
}
if(file) fclose(file); //segfault right here
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fread(&secret,...
,secret 类型为char*
,覆盖 scecret 的值,然后写入文件,而不是写入 Secret 指向的值。fread(&secret,...
with secret being of typechar*
overwrite the value of scecret, and then probaly file, instead of writing into the value pointed by secret.我的猜测是问题就在这里:
您的意思是:
或者也许,
secret
指向的缓冲区实际上并不是size
字节长。 你分配对了吗?My guess is the problem is right here:
Did you mean:
Or maybe, the buffer pointed to by
secret
is not reallysize
bytes long. Did you allocate it correctly?您正在破坏堆栈,用读取“秘密”变量时出错的内容覆盖文件变量。 'secret' 已经是一个指针,所以它不需要 '&' 操作员。
fread 行应该读取
你正在做的基本上是将一个新的指针值读入秘密(而不是秘密指向的内存),并且读取太多,溢出到你的其他变量中。 如果您在此函数中使用了 Secret,它也会出现段错误(希望如此,或者如果您不幸的话,会在程序的其他部分造成随机损坏)。
HTH。
You're smashing your stack, overwriting the file-variable with something borked when reading to the 'secret' variable. 'secret' is already a pointer, so it doesn't need the '&' operator.
The fread line should read
What you're doing is basically reading a new pointer value into secret (instead of the memory where secret is pointing to), and reading way too much, overflowing into your other variables. If you'd used secret within this function it'd have segfaulted as well (hopefully, or caused random damage in other parts of your program if you're unlucky).
HTH.