1
votes

I face critical problem related malloc and free.

'A' thread allocate memory using malloc. and 'A' thread finish.

'B' thread free memory from allocated 'A' thread but some times program is dead.

so i printed memory address but the same malloc address and free address.

how to debug this situation?

please advice to me.

the example code like this

and dlmalloc metadata also same between malloc and free. and if didn't use thread, also occrued same probleam.

umm... allocated memory content modified secure-world operating system.

Polling function
{
    poll((struct pollfd *)&Event, 2 10000);
    read(fd, &index, sizeof(uint));
    pthread_create(&thread[index], NULL, SomeFunction, (void *)index);
    pthread_detach(thread[index]);
}


void SomeFunction(uint *arg) 
{
    uint command;
    command = (uint)arg;

    switch(command) {
        case malloc:
            MallocFunction();
        break;
        case free:
            FreeFunction();
        break;
    }
    Ioctl(fd, .....);
}


MallocFunction() 
{
    uint mem;

    mem = malloc(uint);
}

FreeFunction()
{
    uint mem;

    GetMallocMemory(&mem);

    free((char *)mem);
}
2
Using gdb? Please post a minimum working example of your code that shows the error and we'd gladly take a look! - Fredrik Pihl
Can you provide any output when this fails? Do you have code snippets of the offending code? - Perry Devetzis
You need to make it very clear in your programming who has the responsibility to delete memory and when it happens. You must arrange your program so that the order of operations is guaranteed to be correct. Just guessing and hoping to get it right most of the time is a recipe for disaster. - Zan Lynx

2 Answers

2
votes

In multithreading, you cannot make guarantees on the order of execution of threads unless they are synchronized. In your case, there are chances of thread de-allocating the memory before another thread allocates it.

The code snippet will help further examining the issue.

0
votes

First of all, in your MallocFunction you are assigning an address to an integer variable. Depending on the address length of the machine your code was compiled for, the address might be cut off (32 bit versus 64 bit).

Secondly, you are using a local variable (mem) to save the allocated address. This variable will lose it's scope after the function finishes. I'm curious what your GetMallocMemory function looks like.

Try to fix these problems first.