Вопрос

I have the following code which I can't understand the status after one line in main.

#include <iostream>

typedef unsigned long size_t;

const int MAX_BUFFER=3;
int buf[MAX_BUFFER]={0}; //Initialize to 0
int location=0;

struct Scalar {
    int val;
    Scalar(int v) : val(v) { };

    void* operator new(size_t /*not used*/) {
        if (location == MAX_BUFFER) {
            throw std::bad_alloc();
        } else {
            int* ptr = &buf[location];
            if ( buf[location] == 0) {
                location++;
            } else {
                return ptr;
            }
        }
    }
    void operator delete(void* ptr) {
        size_t my_loc = (int*)ptr - buf;
        buf[my_loc] = location;
        location = my_loc;
    }
};

int main() {
    Scalar *s1 = new Scalar(11);
    cout << buf[0];
}

Why does the array buf in the end of this code contains the value 11 at the...? I'm am not sure where the val input plays a role.

Это было полезно?

Решение

I don't understand why you only conditionally increment location after an allocation, and if you increment location, then the function doesn't execute a return statement which is undefined behavior.

Your deallocation strategy is completely broken unless objects are only deallocated in the exact opposite order of allocations. Additionally, after the array element has been used for one allocation, it won't ever be used again due to the assignment in the deallocator.

As for the actual question: the first Scalar allocated is allocated at the same location as the buffer, so the first Scalar and buf[0] share the same memory. As they're both composed of a single int, writes to one might be readable from the other. And when you construct the Scalar, it assigns the value 11 to the shared memory. I think doing this is undefined behavior, but I'm not certain.

Другие советы

The value 11 gets into the buffer thanks to

Scalar(int v) : val(v) { };

that takes the parameter and copies it into the member val.

If the class instance is allocated at the address of the buffer (because of the customized operator::new (size_t) implementation) then it's possible that its first member ends up in the first array element.

Note that this code is totally broken for several reasons already pointed out by Mooing Duck.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top