Error address when malloc / free pthread_t across threads

The failure occurred when I malloc pthread_t saved the newly created thread id and freed it on another thread. The codes are as follows:

typedef struct _TaskInfo { 
    // int dummy_int;
    pthread_t tid;
} TaskInfo;

void* dummy_task(void* pArg) {
    free(pArg);
    return NULL;
}

void create_task() {
    TaskInfo *pInfo;
    pthread_attr_t attr;

    // set detached state stuff ...

    pInfo = (TaskInfo*) malloc(sizeof(TaskInfo));
    pthread_create(&pInfo->tid, &attr, dummy_task, pInfo);

    // destroy pthread attribute stuff ...
}

int main() {
    int i;
    while(i < 10000) {
        create_task();
        ++i;
    }
    return 0;
}

      

When I uncomment the dummy_int member in TaskInfo, it sometimes runs successfully but sometimes fails. My platform is VMWare + Ubuntu 9.10 + ndk r3

Thanks!

+2


a source to share


1 answer


pthread_create()

stores the thread id (TID) of the created thread at the location pointed to by the first parameter, however it does so after the thread is created ( http://opengroup.org/onlinepubs/007908799/xsh/pthread_create.html ):

Upon successful completion, pthread_create () stores the id of the created thread in the location referenced by the thread



Since the thread has already been created, it might get a chance to start and delete this block of memory before it pthread_create()

gets a chance to store the TID in it.

If you don't have a member dummy_int

in the structure, you are likely to damage the heap in such a way that it crashes earlier. With dick on, dummy_int

you happen to destroy something less sensitive (so glitches are a little less common). Either way, you are destroying memory that is not allocated (or may not be allocated, you have a race condition).

+1


a source







All Articles