Error in Resize() for a Button Class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Error in Resize() for a Button Class

I am trying to make a class to help me create buttons that can be used to read mouse Input during a Console Input event. I was able to create the Button and Image_button Classes and the default functions (Construction, Printing, Clicking), worked just fine. Link : https://github.com/kinshuk-h/Image_Button I then tried to define Setter Functions for these classes to change the position (via Move()) or the size (via Resize()) of the buttons on the screen. The Resize functions for the Image_Buttons class, works fine for a single object, but if I try to define multiple objects, say I1 and I2, and call I1.Resize(), the program returns an error code : 0xC0000005 (Memory Access Violation). If I call I2.Resize() instead, the error code is not returned. I found that the program did reach the end of the function in both the cases, but only in case 2 the program ends successfully. Please help me solve this error. Is this due to Lock()? If yes, why does the program terminate successfully when the Button being resized is the last one?

18th Jul 2018, 7:38 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
3 Answers
+ 6
The error occurs in New_Windows.h at the Release function. The issue is that you try to erase something that isn't there. Reserve assigns the button with some kind of ID based on the index of the vector I assume? Which that button later uses to erase itself at that index. Let us give button 0 the ID of 0 and button 1 the ID of 1 If button 0 erases itself at index 0. The size of the vector changes from 2 to 1. Now button 1 erases itself at index 1 ( but button 1 is now at index 0 ), so it tries to access something that isn't there. This happens at destruction btw, so that's the reason it doesn't crash when there is just 1 button. The main problem you should fix here is to prevent the other ID's from becoming invalid due to an erase. You could use a map. Simply replace static std::vector<SMALL_RECT> Cur_UI_Elm; with static std::map<size_t, SMALL_RECT> Cur_UI_Elm; The size_t would serve as the ID. There are a few ways to assign ID's You could use the size of the map as the ID. e.g. Cur_UI_Elm[Cur_UI_Elm.size()] = R; return Cur_UI_Elm.size()-1; or static size_t ID = 0; Cur_UI_Elm[ID] = R; return ID++; Of course you would have to edit the Reserved function as well. I just did a quick map to vector conversion cause I was too lazy to work out the rest :) Hope it helps, good luck with your project. :)
18th Jul 2018, 9:32 AM
Dennis
Dennis - avatar
+ 2
Dennis Thank you very much for your help. It was silly of me to not think of some update procedure in case a previously reserved button was deleted.
18th Jul 2018, 10:31 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
- 3
ahahaha
19th Jul 2018, 2:28 AM
Marcello Leandro s