Re: data corruption on pointer cast
On 2007-07-16 07:56, gara.matt@gmail.com wrote:
Heyllo,
Names matt,
I implemented a set class as follows:
template<class T>
class Element
{
public:
virtual int operator == (T) = 0;
virtual bool operator==(const T&) = 0;
virtual int hash() = 0;
};
/**
* A efficient hash implementation of a Queue-set that does not allow
addition of duplicates.
@author matt gara <gara.matt@gmail.com>
*/
template<class T, int M = p>
class QueueSet
{
public:
...
int exists(Element<T> * elem)
{
int h = elem->hash()%M;
for (int i=0; i < size_t[h]; i++)
if ( *((T*)elem) == *((T*)set[h][i]))
return 1;
return 0;
}
int add(Element<T> * elem)
{
int h = elem->hash()%M;
if (size_t[h] == max[h])
{
set[h] = (Element<T> **)realloc(set[h], sizeof(Element<T>
*)*(max[h] + P));
Unfortunately I don't think that there's any guarantee that realloc will
work on anything except POD types, which makes it very dangerous to use
in C++.
max[h] += P;
}
if (exists(elem))
return 0; //failed to add
set[h][size_t[h]] = elem;
size_t[h] += 1;
size++;
return 1;
}
...
Element<T> ** set[M];
int size;
private:
int size_t[M];
size_t is the name of a type used extensively throughout the standard
library, using it as an identifier might not be a good idea.
int max[M];
...
};
Sorry, can't help you with your problem, I can only point out some other
things in your code. One thing I noticed was that you use an awful lot
of pointers, try using references instead. Also you might want to make
Element a private class to QueueSet and make it's use transparent to the
user, require instead that the elements are comparable and let the user
supply the hash-function as a template parameter:
template<class T, class H, int M = p>
class QueueSet { ... };
where H is the hash-function.
--
Erik Wikstr?m