Very confused over this. I’ve just started learning about pointers and have now decided to go a bit deeper and start experimenting with threads. What I’m trying to do is pass a pointer onto a thread, so (after mallocing data) I call:
pthread_create(&ptThread, &ptAttr, newClient, (void *) data);
Inside the newClient function, I do what I need to do, and I decided (as there was a pointer allocated) to free it:
void *newClient(void *v) {
// ...stuff happens here...
free(v);
}
At the free(v); part, I get a Segmentation fault. So I used valgrind, and I got this saying it was an invalid free:
==1214== Invalid free() / delete / delete[]
==1214== at 0x4023B6A: free (vg_replace_malloc.c:366)
==1214== by 0x804F622: newClient (xxxxxx2.c:44)
==1214== by 0x4032954: start_thread (pthread_create.c:300)
==1214== by 0x4112E7D: clone (clone.S:130)
==1214== Address 0x4 is not stack'd, malloc'd or (recently) free'd
To add to the fire, as I quit my program, valgrind told me I had a memory leak because v wasn’t free‘d:
==1214== 8 bytes in 2 blocks are definitely lost in loss record 1 of 1
==1214== at 0x4023F50: malloc (vg_replace_malloc.c:236)
==1214== by 0x804F453: main (xxxxxx1.c:94)
My questions – how is it an invalid free? Is there something I’m missing here? Do I need to free(v);?
First of all,
0x4doesn’t look like a valid address.What I think is happening is that you are accidentally changing
v. This may be because of a carelessmemcpy/strcpyoverwriting the stack ofnewClient.On another note, generally it is recommended that both
mallocandfreeare done in the same thread. I heard some allocators are designed to do it more efficiently that way.