Question about THStorage

I have a silly question:

THLongStorage *t1 = THLongStorage_newWithAllocator(2, &THDefaultAllocator, NULL);
THLongStorage_free(t1);

it’s ok.

long data[3] = {2, 3, 5};
THLongStorage *t2 = THLongStorage_newWithDataAndAllocator(data, 3, &THDefaultAllocator, NULL);
THLongStorage_free(t2);

there is an error: process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

thank you advance!!!

THStorage_(newWithDataAndAllocator) assumes the data was allocated by the passed-in allocator. It doesn’t copy the data, it just steals the pointer.

The snippet breaks because data is allocated on the stack but the THLongStorage_free() tries to free it via the allocator (free()).

Instead do something like:

THLongStorage *t1 = THLongStorage_newWithAllocator(3, &THDefaultAllocator, NULL);
THLongStorage_free(t1);

long data[3] = {2, 3, 5};
memcpy(t1->data, data, 3 * sizeof(long));
2 Likes

Thank you colesbury. :grinning: