1

I want to have a concurrent hash map as a member of structure. I am doing it as below:

typedef concurrent_hash_map<int, int> Acreaders;
struct node{ 
    void *obj;  
    int size; // see if required
    Acreaders acrdr;
};

So that i should be able to access to insert into the hash table as:

Acreaders::accessor a;
struct node *n;
n = (struct node *)malloc(sizeof(struct node));
(n->acrdr).insert(a, 5); 

Although the program compiles correctly, it leads to segmentation fault.

What might be the problem? Thanks..

ceedee
  • 227
  • 1
  • 4
  • 13
  • 2
    Have you tried writing your code in C++? (I.e. using `new` , as opposed to using C functions such as `malloc`?). For example, currently the constructor of `n->acrdr` will never be called, which is likely the cause of your segfault. – anderas Jul 21 '15 at 13:44

1 Answers1

3

ceedee,

anderas is correct. mallocing *n does not initialize it, but just allocated space for a node on the heap. If you make it:

Acreaders::accessor a;
node nn;               // this constructs nn
node *n(&nn);          // point n to nn

(n->acrdr).insert(a, 5);

If you want to dynamically allocate node specifically using malloc, you can initialize it like so:

node *n;
n = new(malloc(sizeof(node))) node();  // placement new into space

This allocates space on the heap with malloc, and constructs node into that space with placement new. In this case you must call the destructor before freeing the space:

n->~node();  // destructor frees any additional structures used by node
free(n);

Or as anderas described, you can just say

n = new node();

and after you are done with it, call

delete n;

You should always use new in preference to malloc with C++ (and TBB is a C++ library.) See In what cases do I use malloc vs new?

Community
  • 1
  • 1
cahuson
  • 826
  • 4
  • 10