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;
}
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.