Mysterious freeing

Everything todo with programming goes HERE.
Post Reply
User avatar
Jonathan
A Brave Victim
Posts: 3391
Joined: Thu Feb 03, 2005 12:50 am
Location: Not really lurking anymore

Mysterious freeing

Post by Jonathan »

I just got something really strange, regardless of optimization. I already deleted my code because it was messy and I wanted to do it over again anyway, so you can't have a look at it, but the allocation part was basically:

Code: Select all

struct somestruct {
    void *pointer;
};

struct somestruct function() {
    struct somestruct ret;
    ret.pointer = malloc(123);
    // check after alloc
    printf("pointer=%p\n", ret.pointer);
    printf("size=%u\n", malloc_size(ret.pointer));
    bzero(ret.pointer, 123); // do something with the memory
    // check before return
    printf("pointer=%p\n", ret.pointer);
    printf("size=%u\n", malloc_size(ret.pointer));
    return ret;
}

void anotherfunc() {
    struct somestruct ret = function();
    // final check
    printf("pointer=%p\n", ret.pointer);
    printf("size=%u\n", malloc_size(ret.pointer));
}
It would print something like:

Code: Select all

pointer=0x2008000
size=4096
pointer=0x2008000
size=4096
pointer=0x2008000
size=0
and crash when referencing the memory.

Any idea what could be happening?
ˌɑrməˈɡɛˌtrɑn
User avatar
Jonathan
A Brave Victim
Posts: 3391
Joined: Thu Feb 03, 2005 12:50 am
Location: Not really lurking anymore

Post by Jonathan »

I got the rewrite done and it's working fine (and several orders of magnitude faster, even without optimizer!), but I'm still wondering what could have caused it.
ˌɑrməˈɡɛˌtrɑn
User avatar
Lucifer
Project Developer
Posts: 8641
Joined: Sun Aug 15, 2004 3:32 pm
Location: Republic of Texas
Contact:

Post by Lucifer »

Looks like, for some reason, your struct went out of scope, although I can't see why that would happen.
Image

Be the devil's own, Lucifer's my name.
- Iron Maiden
User avatar
Jonathan
A Brave Victim
Posts: 3391
Joined: Thu Feb 03, 2005 12:50 am
Location: Not really lurking anymore

Post by Jonathan »

It didn't (out of scope means you can't reach it, but I can), and why would it free something inside the struct?
ˌɑrməˈɡɛˌtrɑn
Post Reply