My code works perfectly when I make the buffer I use in fread and fwrite an array of unsigned chars, but when I use malloc to allocate memory space I get segmentation faults (this is the opposite of what I thought was supposed to happen). I am freeing the space at the very end of the code and the line where I'm using malloc looks like this:

unsigned char *buffer = malloc(sizeof(unsigned char)*512); 

What am I doing wrong?


Are you passing the address of buffer to fread or just buffer? fread(buffer ...) If you're passing the address, like fread(&buffer ...) then you'll segfault because it's trying to read into the address where your buffer pointer is stored, not the actual memory that you've malloced). Remember, fread takes a pointer as its first argument.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .