I get an access violation error when I use a self written Buffer class:
template<typename T>
class Buffer {
public:
Buffer(T *data, size_t len);
Buffer(size_t len);
size_t len();
operator T*();
T& operator[] (const int x) const {
return this->data[x];
};
private:
T *data;
size_t _len;
};
int main() {
Buffer<char> b("123", 3);
b[0] = 0; // This line causes "Access violation writing location 0x003c8830".
return 0;
}
Why is that? What am I doing wrong?
The code that causes the issue is not in the post, but it’s very likely your constructor: if you assign the pointer
datato the memberdata, then you store the string constant inside your class. Then code of themainthan tries to write into non-writable memory, causing access violation.You can fix your constructor to avoid this problem: