Can someone tell me why this code segfaults? I've read the man pages for both malloc and free and everything seems in order. Furthermore, most issues seem to come from assigning strings to memory allocated by malloc, but that is clearly not the issue here.

FILE *inFile = fopen(inptr, "r");
if(inFile == NULL){
    fprintf(stderr, "Couldn't open input file\n");
    return 2;

FILE *outFile = fopen(outptr, "w");
if(outFile == NULL){
    fprintf(stderr, "Couldn't create output file\n");
    return 2;

char *temp = malloc((fileLength + 1)* sizeof(char));

fread(&temp, fileLength, 1, inFile);
fwrite(&temp, sizeof(temp), 1, outFile);


  • Which line is causing the segfault? Also, can you post the code that declares and opens inFile and outFile as well as the code for filelength? If a file isn't properly opened, or if the file pointer is null, it will cause a segfault. (Please edit the question and add the missing code there, not as a comment.)
    – Cliff B
    Aug 2 '17 at 21:33
  • I've added the IO code, but I'm sure that's not the issue because I can edit the read data just fine. I should have clarified that it is the last line, free(temp); which cause the segfault.
    – colossal
    Aug 2 '17 at 23:46

Two problems:

  1. temp is a pointer (address) by itself and you allocate some memory started at this address by malloc. &temp is another address temporarily created by computer as a pointer to temp. You need to read from and write to temp, not &temp.

  2. temp is a variable of pointer type. So sizeof(temp) == sizeof(type pointer) == 8 (for 64bit system), no matter what fileLength is. In the same manner as sizeof(1) == sizeof(1000000) == sizeof(type int) = 4.

You must log in to answer this question.

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