简体   繁体   中英

What does buffer overrun error in uint32_t mean?

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?

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 ie

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)
    {}
    //...
}

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