Andre Garzia
Andre Garzia

Reputation: 983

C pointer trouble: it loses address information when returned from a function

I have some C code here where a pointer is allocated and returned to the parent caller/parent function. Using GDB, I noticed that the pointer allocation is fine but when I return it, it loses the high bits of the first four bytes of the address. Basically it goes like this:

allocate pointer A
allocate pointer B
Free A
Return B

Now, if I change this to:

allocate pointer B
allocate pointer A
Free A
Return B

Things work fine. What is strange is that this code worked fine for 5+ years and now it is giving us trouble on some very specific cases. What worries us is that the address is changed, we could not detect this error in any other way, only when we attached gdb and started looking around we saw the change.

Anyone here seen something similar or knows why this is happening? By the way, we are not trying to write more than we can handle in A or B, both buffers are the right size for the data.

thanks in advance for any clue.

Upvotes: 3

Views: 1067

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

This is almost surely due to memory corruption, i.e. writing to random addresses or past the end of an allocated object or object on the stack.

Upvotes: 0

Kakira
Kakira

Reputation: 856

This could be due to many reasons, overflow of buffers, limited heap space etc. Posting code would help!

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78903

Smells like you didn't declare a prototype of your function. This went well for years on 32bit machines where int and void* have the same width. Nowadays these are different, and you loose your high order bytes.

You compile with -Wall or something like that, I suppose?

Upvotes: 4

Related Questions