分配专用缓冲区并使用指针修改内容



我想用allocate_buffer(...)函数为类A中的私有uint32_t数组分配内存,该函数采用数组的大小和未初始化的指针(void *data(指针。

指针应用于访问A::buffer的内存,这样就可以使用memcpy(...)将数据复制到具有的阵列中

memcpy(pointer_to_buffer, some_src_data, sizeof(some_src_data));

prg.hpp

具有专用缓冲区的类以及用于分配和打印的功能

#ifndef PRG_HPP
#define PRG_HPP
#include <cstdint>
#include <stddef.h>
#include <cstdlib>
#include <iostream>
class A {
private:
void *buffer;
size_t count;
public:
void allocate_buffer(size_t size, void **data) {
buffer = malloc(size);
count = size;
data = &buffer;
}
void print_buffer() {
auto data = (uint32_t*)buffer;
for (size_t i = 0; i < count; i++) {
std::cout << data[i] << std::endl;
}
}
};
#endif

main.cpp

一个简单的程序,它使用prg.hpp

#include "prg.hpp"
#include <iostream>
#include <vector>
#include <cstring>
int main(void) {
// An objected of class A gets created
A a = {};
// A simple vector with ints up to 100, which acts as the src for malloc
std::vector<uint32_t> ints;
for (int i = 0; i < 100; i++) {
ints.push_back(i);
}
// buffer of object a is allocated and data should now be a pointer to the buffer
void *data;
size_t size = sizeof(uint32_t) * ints.size();
a.allocate_buffer(size, &data);
// Using the pointer to copy the contents of the vector ints to the buffer of object a
memcpy(data, ints.data(), size);
// Presentation
a.print_buffer();
return 0;
}

PS:执行产生segfault

罪魁祸首是:

void allocate_buffer(size_t size, void **data) {
buffer = malloc(size);
count = size;
data = &buffer;  // damned!
}

在函数或方法中,参数是局部变量,如果更改它们,则只会更改一个在函数结束时消失的局部变量(其生命周期以C++语言结束(。

您正确地传递了指针的地址:只需使用它:

*data = buffer;  // good...

这样就可以更改调用方指针的值。


但正如您在评论中所说,这种低级别内存操作不是C++惯用的方式。测试和学习没有什么不好的,但在没有充分理由的情况下,不要在现实世界中这样做。

最新更新