Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsearch and tfind

Given sizeof(void*) >= sizeof(int), is it safe to collect ints in tree with

void *map=0; 
tsearch(42, &map, int_cmp);

?

I get segfault and I see no flaws in code other then that unusial usage.

EDIT: Of course, I am not derefencing pointer, only convert back to int. Idea is that int can be fitted into void* variable, so i have no need for heap allocation.

like image 635
KAction Avatar asked Jan 31 '26 16:01

KAction


1 Answers

The first parameter to tsearch must be a pointer. In this case the number 42 is interpreted as a pointer, hence the segfault. Try:

void *map=0;
int key = 42;  
tsearch(&key, &map, int_cmp); 
like image 61
Attila Avatar answered Feb 03 '26 06:02

Attila