开发者

Seg Fault with malloc'd pointers

开发者 https://www.devze.com 2022-12-30 05:04 出处:网络
I\'m making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a开发者_JAVA技巧 queue, but I\'m having trouble with it. It seems to allocate and fill the queue struct fine

I'm making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a开发者_JAVA技巧 queue, but I'm having trouble with it. It seems to allocate and fill the queue struct fine, but when I try to get the data from it, it Seg. faults.

http://pastebin.com/Bquqzxt0 (the printf's are for debugging, both throw seg faults)

edit: the queue is stored in a dynamically allocated "struct queueset" array as a pointer to the data and an index for the data


C++ provides a built-in queue class for you:

#include <queue>

struct queueset
{
    void* ptr;
    int index;

    queueset(void* p, int i) : ptr(p), index(i) {}
};

class pthreadmutexlock
{
public:
    pthreadmutexlock()
    {
        pthread_mutex_init(&lock, NULL);
        pthread_mutex_lock(&lock);
    }

    ~pthreadmutexlock()
    {
        pthread_mutex_unlock(&lock);
        pthread_mutex_destroy(&lock);
    }
private:
    pthread_mutex_t lock;
};

class ThreadSafeQueue
{
public:
    void add(void* msg, int index);
    queueset get();
    bool hasitems() const { return !queue.empty(); }
private:
    std::queue<queueset> queue;
    pthread_mutex_t lock;
};

void ThreadSafeQueue::add(void* msg, int index)
{
    pthreadmutexlock lock;
    queue.push(queueset(msg, index));
}

queueset ThreadSafeQueue::get()
{
    pthreadmutexlock lock;
    queueset temp = queue.front();
    queue.pop();
    return temp;
}

In C++, the best way to avoid memory problems is to minimize the management of memory using raw pointers as much as possible, and use standard classes where applicable.

0

精彩评论

暂无评论...
验证码 换一张
取 消