简体   繁体   中英

Allocating a private buffer and using a pointer to modify the contents

I want to allocate memory for a private uint32_t array in the class A with the allocate_buffer(...) function, which takes the size of the array and an uninitialized pointer ( void *data ) pointer.

The pointer should be used to access the memory of A::buffer , such that it is possible to use memcpy(...) to copy data to the array with

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

prg.hpp

the class with a private buffer and to functions for allocating and printing

#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

a simple program, which uses 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: Execution gives a segfault

Here is the culprit:

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

In a function or method, the parameters are local variables and if you change them you only change a local variable which vanishes at the end of the function (its lifetime is ended in C++ wordings).

You correctly passed the address of a pointer: just use it:

        *data = buffer;  // good...

That way you change the value of the caller's pointer.


But as you have been told in comment, such low level memory operation is not the C++ idiomatic way. There is nothing bad in testing and learning, but do not do that in real world programs without a strong reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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