views:

300

answers:

3

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;
}
+7  A: 

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

RetVal=fread(secret,1,size,file);

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.

roe
Can't believe I did something that stupid. Thanks.
Belrog
+1 for the winning combination of correct answer and good explanation.
Chris Lutz
...and if your compiler didn't warn you about the pointer conversion on the fread() line, then that probably means that you didn't #include <stdio.h>
caf
+4  A: 

My guess is the problem is right here:

RetVal=fread(&secret,1,size,file);

Did you mean:

RetVal=fread(secret,1,size,file);

Or maybe, the buffer pointed to by secret is not really size bytes long. Did you allocate it correctly?

1800 INFORMATION
+3  A: 

fread(&secret,... with secret being of type char* overwrite the value of scecret, and then probaly file, instead of writing into the value pointed by secret.

AProgrammer