0

I'm trying to write ARGB color data into a uint32_t variable through a for loop. I get an error:

invalid write to m_imagedata[i][1],wriable range is 0 to 0

if (!render){
    uint32_t* m_imagedata = nullptr;
}
else{
    m_imagedata = new uint32_t(m_viewportheight * m_viewportwidth);
}
        
for (uint32_t i = 0; i < m_viewportheight * m_viewportwidth; i++) {
    m_imagedata[i] = 0xff00ffff;

How can I fix this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 5
    You want `new[]` not `new()` which creates single `uint32_t` and initializes it with that value, but better use `std::vector` not only it would solve your memory problems, it will eliminate your loop – Slava Aug 30 '22 at 17:14
  • And after you make that change once you are done with the array you need to use `delete [] m_image_data;` to release the memory. That said, you can just use a std::vector` and not have to worry about manual memory management. – NathanOliver Aug 30 '22 at 17:16
  • 1
    *How can I fix this?* `std::vector`. *I'm noob in c++* C++ noobs should not use `new` (it's advanced C++). – Eljay Aug 30 '22 at 17:23
  • Are you declating a local variable with teh same name as a member variable on purpose? `uint32_t* m_imagedata = nullptr;` has no effect and almost certainly will be optimized out. If you make this an assignment to the member variable, you'll end up with UB, if `!renderer` yields `true`... – fabian Aug 30 '22 at 17:45
  • `uint32_t* m_imagedata = nullptr;` does not do what you think it does. – Sam Varshavchik Aug 30 '22 at 18:57

1 Answers1

1

You have the syntax for dynamically allocating an array wrong. It should be

m_imagedata = new uint32_t[m_viewportheight * m_viewportwidth];

and then you'd have to delete it using the delete[] form of delete i.e.

delete[] m_imagedata;

However, as others have noted in comments if what you want is an array that can be dynamically sized at runtime, you should use the one that is included in the C++ standard library: std::vector<T>. This way you do not need a loop to initialize each item to some value and you don't have to worry about deleting it yourself. If your m_imagedata member variable is a std::vector<uint32_t> you can initialize it in the constructor of your class like:

class my_image_class {
    //...
    std::vector<uint32_t> m_imagedata;
public:
    my_image_class(int wd, int hgt) :
        m_imagedata(wd * hgt, 0xff00ffff)
    {}
    //...
}
jwezorek
  • 8,592
  • 1
  • 29
  • 46