c++ - 使用 malloc 指针的段错误

标签 c++ pointers malloc segmentation-fault

我正在制作一个线程类用作 pthreads 的包装器。我有一个 Queue 类用作队列,但我遇到了麻烦。它似乎可以很好地分配和填充队列结构,但是当我尝试从中获取数据时,它会分段。故障。

http://pastebin.com/Bquqzxt0 (printf 用于调试,都抛出段错误)

编辑:队列存储在动态分配的“struct queueset”数组中,作为指向数据的指针和数据的索引

最佳答案

C++ 为您提供了一个内置的队列类:

#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;
}

在 C++ 中,避免内存问题的最佳方法是尽可能减少使用原始指针的内存管理,并在适用的情况下使用标准类。

关于c++ - 使用 malloc 指针的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2843030/

相关文章:

c++ - 指针: &foo == foo?的指针

c - 插入二叉搜索树

c - 内置函数的隐式声明不兼容 ‘malloc’

c++ - 当 CPU 使用率高时,OpenCV 会堆积内存吗?

C++/Qt : Get files in directory ordered according to sorting currently applied in Windows Explorer

c - C 中的数组递增运算符

c - C 中的动态分配 - 分配到函数中

c++ - Qt 的 CUDA 包装器

c++ - 通过引用传递智能指针

c++ - 拥有对象实例与拥有指针