zaugri
zaugri

Reputation: 31

fwrite fails (returns 0, perror gives "Bad address")

What are the possible reasons for such an error. File being written to is created without a problem, but fwrite fails each time.

I am porting from 32-bit little endian to 64-bit big endian.

The structure I am writing is

struct Node 
{
uint8_t *a;
uint32_t *b;
uint32_t c;
uint32_t d;
uint32_t e;
uint32_t f;     
uint32_t g; 
uint16_t h; 
uint8_t i;  
uint8_t j;  
uint8_t k[MAX];
uint32_t (*l)[2];
uint32_t m; 
uint32_t n;

Node() {
    memset(this, 0, sizeof(*this));
    l = NULL;
    a = (uint8_t*)calloc(N,1);
}
~Node() {
    free(a);
    free(b);
}
};

The code writing the node is

void push(void *ptr)
{
Node *node = (Node *) ptr;
assert(fwrite(node, sizeof(Node), 1, fpw) == 1);
    free(node);
}

fpw has a global scope.

When I tried to debug, I found that fwrite returns 0 and perror gives "Bad address" as the error.

Any suggestions would be appreciated.

Upvotes: 0

Views: 1816

Answers (1)

littleadv
littleadv

Reputation: 20282

I'm not sure I have an answer for you here, but I think its worth pointing out a bunch of things that I see in your code. Solving them, I would hope, will help you overcoming your problem.

  1. When you have a class that you want to dump into a file - have the class do the work for you. That means, your Node class will have a write/read set, or operator<</operator>> or any other conventional set of routines that you will call, and have it serialize itself into a file and then deserialize itself from a file on read. Boost provides you tools to help with that, as well.

  2. Dumping a content of a class pointer is a dangerous thing, especially if you're dumping on one architecture, and reading on another (in your case 32LE vs 64BE). It will most certainly fail in a whole bunch of various unpredictable ways.

  3. You access a pointer you got from somewhere without verifying its valid. I don't know if you have a test on your ptr before you call push, but I'm sure it will be helpful to check the pointer in push itself, especially if the error suggests it might not be good.

  4. You're writing C++ code. You're destroying a class. free shouldn't be anywhere in your code! You're creating Node* node with malloc? I would hope not! If you're using new you must use delete.

  5. You're freeing a and b in your ~Node, but you don't allocate them anywhere. If you're not allocating it in the constructor - when you delete it in the destructor - verify that you allocated them, otherwise you'll get bunch of undefined behavior here too.

Just some things that couldn't help but noticing, hope it helps.

Upvotes: 1

Related Questions