Why is alloca returning the same address twice?

  alloca, allocation, arrays, c++

I’m trying to implement my own math library, and I’m starting off with vectors. The idea is to give the class a pointer to an array of numbers, then copy the array and store it in the data address given by a private variable pointer. To begin with, I used alloca to try and free up some memory for the private variable

vml.h

namespace vml {
    // Vectors
    template <typename in_type, const int in_length>
    class vec {
    public:
        vec(in_type* in_data) {
            std::cout << data << std::endl;
            std::copy(in_data, in_data + in_length, data);
        }
        vec() {
            data = nullptr;
        }
        in_type& operator()(int index) const {
            _ASSERT(0 <= index && index < in_length);
            return data[index];
        }

    private:
        in_type* data = alloca(in_length * sizeof(in_type));
    };

main.cpp

int main() {
    int list[] = { 1,2,3 };
    int list2[] = {2,4,6 };

    vml::vec<int, 3> a(list);
    vml::vec<int, 3> b(list);

    return 0;
}

This gives no errors however, for some reason, alloca returns the same address twice when calling two instances. I searched this up everywhere and I couldn’t find an explanation why. So I decided to allocate memory using an array.

vml.h

namespace vml {
    // Vectors
    template <typename in_type, const int in_length>
    class vec {
    public:
        vec(in_type* in_data) {
            std::cout << data << std::endl;
            std::copy(in_data, in_data + in_length, data);
        }
        vec() {
            data = nullptr;
        }
        in_type& operator()(int index) const {
            _ASSERT(0 <= index && index < in_length);
            return data[index];

        }

    private:
        in_type data[in_length];
    };

main.cpp

#include <memory>
#include "vml.h"

int main() {
    int list[] = { 1,2,3 };
    int list2[] = {2,4,6 };

    vml::vec<int, 3> a(list);
    vml::vec<int, 3> b(list);
    
    a(1);
    
    return 0;
}

The good news is that the array doesn’t allocate the same memory twice (you can test this by removing a(1)). However, if I run this code I get an error

Error C2440 'return': cannot convert from 'const in_type' to 'in_type &'

Since the only variable in this function that uses in_type is data this must mean that data is constant even though I did not define it as such.
If you can answer either of these questions that would be extremely helpful.
Thanks.

Source: Windows Questions C++

LEAVE A COMMENT