0

I've finished writing the recover function and made it to compile successfully. However, it gives out a segmentation fault every time I try to run it. I ran valgrind and the error was in the first if condition in the while loop. I assume I am not utilizing the variable buffer properly, but I have been googling and checking stackoverflow for quite a while but I can't get at the cause of the problem. Any help would be GREATLY appreciated!

Here's my code:

/**

[removed code per Honor Code]

2

It clearly doesn't like the tests in the if statement, buffer[0] == (char)0xff seems to be making it choke. There's an easy fix that makes it work though. Change the declaration of your buffer. Instead of

    char* buffer = malloc(512);

change it to

    char buffer[512];

This will make your test conditions work. Also, you'll need to delete the free(buffer) command at the end of the program.

That will fix it, but I'll defer to someone like @kareem to explain exactly why it is throwing a seg fault.

If this answers your question, or if someone else gives an answer that you like better, please accept the answer to remove your question from the unanswered question pool. Let's keep up on forum maintenance. ;-)

1
  • EXACTLY FIXED MY PROGRAM! I will look more into the specific reason as you have suggested. Thank you once again!
    – Xiggi
    Jun 21 '15 at 23:25
2

You are getting segfault because you are declaring a char* buffer = malloc(512) which is your pointer to a block of 512 bytes of memory. But later, when you read in the bytes, you are reading into &buffer which is the address that holds the pointer to the 512 bytes. It can't hold 512 bytes itself, so you segfault.

Change your fread to fread(buffer ...) and your segfault will disappear.

You must log in to answer this question.

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