简体   繁体   English

将通用值复制到无符号char数组,然后用C ++复制回来

[英]Copying generic values to unsigned char array and copying back in C++

I have a class in C++ that represents a buffer where I can store unsigned char . 我在C ++中有一个类,它代表一个缓冲区,可以在其中存储unsigned char I have two methods, one the add generic values using templates and another to retrieve the values. 我有两种方法,一种是使用模板添加通用值,另一种是检索值。 When I am trying to retrieve the values I am getting Segmentation fault (core dumped) . 当我尝试检索值时,我遇到了Segmentation fault (core dumped) I am using memcpy If I change to use std::copy(value, value, _valueChar); 我正在使用memcpy如果更改为使用std::copy(value, value, _valueChar); I get other errors: error: no type named 'value_type' in 'struct std::iterator_traits<int>' 我收到其他错误: error: no type named 'value_type' in 'struct std::iterator_traits<int>'

#include <iostream>
#include <cstring>
#include <utility>
#include <vector>
#include <string>

class SkinnyBuffer {
private:
    unsigned char *_valueChar;
    std::size_t _sizeChar;
public:
    SkinnyBuffer();
    SkinnyBuffer(std::size_t size);
    ~SkinnyBuffer();
    void clean();

    template<typename T>
    void addValue(T value) {
        if (_valueChar != nullptr) {
            delete[] _valueChar;
        }
        // _sizeChar = n; // assume _size is a field
        // _valueChar = new unsigned char[_sizeChar];
        // std::copy(value, value, _valueChar);
        memcpy(_valueChar, &value, sizeof(value));
    }

    template<typename T>
    void addValue(std::size_t offset, T value) {
        if (_valueChar != nullptr) {
            delete[] _valueChar;
        }
        // _sizeChar = n; // assume _size is a field
        // _valueChar = new unsigned char[_sizeChar];
        // std::copy(value, value + offset, _valueChar);
        memcpy(_valueChar + offset, &value, sizeof(value));
    }

    unsigned char *getValue() {
        return _valueChar;
    }
};
#include "SkinnyBuffer.h"

SkinnyBuffer::SkinnyBuffer() {
}

SkinnyBuffer::SkinnyBuffer(std::size_t size) {
    _sizeChar = size;
    _valueChar = new unsigned char[_sizeChar];
}

SkinnyBuffer::~SkinnyBuffer() {
}

void SkinnyBuffer::clean() {
    _valueChar = new unsigned char[_sizeChar];
}

int main(int argc, char *argv[]) {

    int value = 50;
    int offset = sizeof(value);
    SkinnyBuffer b(offset);
    b.addValue(value);

    int dValue;
    memcpy(&dValue, b.getValue(), offset);
    std::cout << dValue << std::endl;
}

In addValue you explicitly delete the _valueChar buffer. addValue您明确删除_valueChar缓冲区。 Then the next line along you write into the deleted buffer. 然后,沿着的下一行写入已删除的缓冲区。 What did you expect this code to do? 您期望这段代码做什么?

This is the first of many issues in your code regarding memory management. 这是代码中有关内存管理的许多问题中的第一个。

Just use a std::vector and as long as its big enough you wont have any of those issues. 只需使用std::vector ,只要它足够大,您就不会遇到任何这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM