unhandled exception Access violation writing location in Visual Studio - c++

Is there a way in Visual Studio 2005 to find out which pointer or variable is causing this access violation? I tried to run in debug mode and break when it happens. By looking at the call stacks, it happens in the end of the function (see below). Could using try/catch be able to find out which pointer it is?
EDIT:
Posting my code:
There is a Qt line edit and a checkbox in my application. Toggling the checkbox would switch the data format in the line edit. Like 3'b111 <==> 3'h7. Below is the callback function that is connected to the checkbox stateChanged signal. The exception happens in the end of function, when destructing local variables.
// switch hex/binary format. 15'h0000 <==> 15'b000000000000000
void switchDataFormat(int checkState) {
QLineEdit* writeRegLE = this->getWriteRegLineEdit();
string oldText = writeRegLE->text().toStdString();
string newText = "";
int maxLength;
string regLengthText = oldText.substr(0, oldText.find('\''));
string regValueText = oldText.substr(oldText.find('\'')+2);
int regLength = this->getRegLength();
if (checkState == Qt::Unchecked) {
// switch to binary format
maxLength = regLengthText.size() + 2 + regLength;
string binaryText;
for (int i = 0; i < regValueText.size(); ++i) {
binaryText += hexToBinary(regValueText[i]);
}
newText = regLengthText + "'b" + binaryText.substr(binaryText.size()-regLength); // trimming leading zeros to fit regLength
}
else {
// switch to hex format
maxLength = regLengthText.size() + 2 + regLength/4 + 1;
newText = regLengthText + "'h";
// zero filling to 4*n bits
if (regLength%4 != 0) regValueText = string(regLength%4,'0') + regValueText;
for (int i = 0; i < regValueText.size(); i+=4) {
newText += binaryToHex(regValueText.substr(i,4));
}
}
writeRegLE->setMaxLength(maxLength);
writeRegLE->setText(QString::fromUtf8(newText.c_str()));
}

Related

Setting a protobuf item's value replaces a previously set variable as well

I have created a simple Protobuf based config file and have been using it without any issues until now. The issue is that I added two new items to my settings (Config.proto) and now whatever value I set for the last variable is reflected in the previous one.
The following snapshot demonstrates this better. As you can see below, the value of fv_shape_predictor_path and fv_eyenet_path depend solely on order of being set. the one that is set last changes the others value.
I made sure the cpp files related to Config.proto are built afresh. I also tested this under Linux and there it works just fine. It seems its only happening in windows! it also doesn't affect any other items in the same settings. its just these two new ones.
I have no idea what is causing this or how to go about it. For reference this is how the protobuf looks like:
syntax = "proto3";
package FVConfig;
message Config {
FV Configuration = 4 ;
message FAN_MODELS_WEIGHTS{
string fan_2DFAN_4 = 1;
string fan_3DFAN_4 = 2;
string fan_depth = 3;
}
message S3FD_MODELS_WEIGHTS{
string s3fd = 1;
}
message DLIB_MODELS_WEIGHTS{
string dlib_default = 1;
}
message MTCNN_MODELS_WEIGHTS {
string mt_onet = 1;
string mt_pnet = 2;
string mt_rnet = 3;
}
message FV_MODEL_WEIGHTS {
string r18 = 1;
string r50 = 2;
string r101 = 3;
repeated ModelContainer new_models_weights = 4;
message ModelContainer{
string model_name = 1;
string model_weight_path = 2;
string description = 3;
}
}
message FV {
MTCNNDetectorSettings mtcnn = 1 ;
FaceVerificationSettings fv = 2 ;
}
message MTCNNDetectorSettings {
Settings settings = 1;
MTCNN_MODELS_WEIGHTS model_weights = 4;
message Settings {
string mt_device = 2;
int32 mt_webcam_source = 100;
int32 mt_upper_threshold = 600;
int32 mt_hop = 700;
}
}
message FaceVerificationSettings {
Settings settings = 1;
FV_MODEL_WEIGHTS model_weights = 2;
message Settings {
string fv_model_name = 1;
string fv_model_checkpoint_path = 2;
bool fv_rebuild_cache = 3;
bool fv_short_circut = 6;
bool fv_accumulate_score = 7;
string fv_config_file_path = 10;
string fv_img_bank_folder_root = 11;
string fv_cache_folder = 12;
string fv_postfix = 13;
string fv_device = 14;
int32 fv_idle_interval = 15;
bool fv_show_dbg_info = 16;
// these are the new ones
string fv_shape_predictor_path = 17;
string fv_eyenet_path = 18;
}
}
} //end of Config message
What am I missing here? How should I be going about this? Restarting Windows and Visual Studio didn't do any good either. I'm using protobuf 3.11.4 both on Linux and Windows.
This issue seems to only exist in the Windows version of Protobuf 3.11.4 (didn't test with any newer version though).
Basically what happened was that I use to first create a Config object and initialize it with some default values. When I added these two entries to my Config.proto, I forgot to also add an initialization entry like other entries, thinking I'm fine with the default (which I assumed would be "").
This doesn't pose any issues under Linux/G++ and the program builds and runs just fine and works as intended. However under Windows this results in the behavior you just witnessed i.e. setting any of those newly added entries, would also set the other entries values. So basically I either had to create a whole new Config object or had to explicitly set their values when using the load_default_config.
To be more concrete this is the snippet I used for setting some default values in my Protobuf configs.
These reside in a separate header called Utility.h:
inline FVConfig::Config load_default_config()
{
FVConfig::Config baseCfg;
auto config = baseCfg.mutable_configuration();
load_fv_default_settings(config->mutable_fv());
load_mtcnn_default_settings(config->mutable_mtcnn());
return baseCfg;
}
inline void load_fv_default_settings(FVConfig::Config_FaceVerificationSettings* fv)
{
fv->mutable_settings()->set_fv_config_file_path(fv::config_file_path);
fv->mutable_settings()->set_fv_device(fv::device);
fv->mutable_settings()->set_fv_rebuild_cache(fv::rebuild_cache);
...
// these two lines were missing previously and to my surprise, this was indeed
// the cause of the weird behavior.
fv->mutable_settings()->set_fv_shape_predictor_path(fv::shape_predictor_path);
fv->mutable_settings()->set_fv_eyenet_path(fv::eyenet_path);
auto new_model_list = fv->mutable_model_weights()->mutable_new_models_weights()->Add();
new_model_list->set_model_name("r18");
new_model_list->set_description("default");
new_model_list->set_model_weight_path(fv::model_weights_r18);
}
inline void load_mtcnn_default_settings(FVConfig::Config_MTCNNDetectorSettings* mt)
{
mt->mutable_settings()->set_mt_device(mtcnn::device);
mt->mutable_settings()->set_mt_hop(mtcnn::hop);
....
}
Not sure this counts as a bug in Protobuf, or my wrong approach here.

QML/C++ coloring every 8th character in a QString

I am making a converter to convert a string to binary and I want to change the color of every 8th character of the resulting binary conversion result to red to symbolize the beginning of each ascii character. The user enters a string a text input and the converted result is displayed in a text area like so:
Every 8th 0 or 1 should be red.
I'm not sure where to begin and is this even possible? And if I were to reverse the converter (user enters binary and its converted to ascii characters) could it still work? Thanks.
Edit:
I am adding "<font color='red'>" and "</font>" to the beginning and end of every eighth binary digit but the result displayed is literally "<font color='red'>0</font>", it is not applying the html styling.
My TextInput sets the TextArea.text whenever the user types using a C++ function.
TextInput {
...
onTextChanged: {
uiText.setBinaryString(myTextInput.text)
myTextAreaText.text = uiText.getBinaryString()
}
}
C++ functions
void UITextConnector::setBinaryString(QString s)
{
binaryString = convertToBinary(s);
}
QString UITextConnector::getBinaryString()
{
return binaryString;
}
QString UITextConnector::convertToBinary(QString qs)
{
std::string resultString;
if (binaryMode) {
std::string qStringConverted = qs.toStdString();
for (std::size_t i = 0; i < qStringConverted.size(); i++) {
std::bitset<8> b(qStringConverted.c_str()[i]);
std::string nextBinary = b.to_string();
nextBinary = "<font color='#00AA00'>" + nextBinary.substr(0,1) + "</font>" + nextBinary.substr(1);
resultString += nextBinary;
}
} else {
std::string qStringConverted = qs.toStdString();
for (std::size_t i = 0; i < qStringConverted.size() ; i = i + 8) {
resultString += UITextConnector::strToChar(qStringConverted.substr(i, i+8).c_str());
}
}
return QString::fromStdString(resultString);
}
However, this only works if I use a label but not when I use a textArea.
Since you didn't provide any source or whatever it is too difficult to understand what is your fail. Anyway, I would do that in the following way:
TextArea {
id: txt
anchors.fill: parent
anchors.margins: 10
textFormat: TextEdit.RichText
text: ""
function setText(str)
{
var arr = str.match(/.{1,8}/g) || [];
var result = "";
for(var index in arr)
{
result += "<font color='red'>" + arr[index].substring(0, 1) + "</font>" + arr[index].substring(1);
}
txt.text = result;
}
Component.onCompleted: {
txt.setText("aaaaaaaabbbbbbbbccccccccdddd");
}
}

Can't get the proper Index to return

Alright, so firstly I want to thank everyone for helping me so much in the last couple weeks, here's another one!!!
I have a file and I'm using Regex to find how many times the term "TamedName" comes up. That's the easy part :)
Originally, I was setting it up like this
StreamReader ff = new StreamReader(fileName);
String D = ff.ReadToEnd();
Regex rx = new Regex("TamedName");
foreach (Match Dino in rx.Matches(D))
{
if (richTextBox2.Text == "")
richTextBox2.Text += string.Format("{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
else
richTextBox2.Text += string.Format("\n{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
}
and it was returning completely incorrect index points, as pictured here
I'm fairly confident I know why it's doing this, probably because converting everything from a binary file to string, obviously not all the characters are going to translate, so that throws off the actual index count, so trying to relate that back doesn't work at all... The problem, I have NO clue how to use Regex with a binary file and have it translate properly :(
I'm using Regex vs a simple search function because the difference between each occurrence of "TamedName" is WAY too vast to code into a function.
Really hope you guys can help me with this one :( I'm running out of ideas!!
The problem is that you are reading in a binary file and the streamreader does some interpretation when it reads it into a Unicode string. It needed to be dealt with as bytes.
My code is below.(Just as an FYI, you will need to enable unsafe compilation to compile the code - this was to allow a fast search of the binary array)
Just for proper attribution, I borrowed the byte version of IndexOf from this SO answer by Dylan Nicholson
namespace ArkIndex
{
class Program
{
static void Main(string[] args)
{
string fileName = "TheIsland.ark";
string searchString = "TamedName";
byte[] bytes = LoadBytesFromFile(fileName);
byte[] searchBytes = System.Text.ASCIIEncoding.Default.GetBytes(searchString);
List<long> allNeedles = FindAllBytes(bytes, searchBytes);
}
static byte[] LoadBytesFromFile(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
//BinaryReader br = new BinaryReader(fs);
//StreamReader ff = new StreamReader(fileName);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
fs.Close();
return ms.ToArray();
}
public static List<long> FindAllBytes(byte[] haystack, byte[] needle)
{
long currentOffset = 0;
long offsetStep = needle.Length;
long index = 0;
List<long> allNeedleOffsets = new List<long>();
while((index = IndexOf(haystack,needle,currentOffset)) != -1L)
{
allNeedleOffsets.Add(index);
currentOffset = index + offsetStep;
}
return allNeedleOffsets;
}
public static unsafe long IndexOf(byte[] haystack, byte[] needle, long startOffset = 0)
{
fixed (byte* h = haystack) fixed (byte* n = needle)
{
for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext < hEnd; hNext++)
for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)
if (++nInc == nEnd)
return hNext - h;
return -1;
}
}
}
}

Output formatted text to Screen

I have a vector that stores pairs. Each pair contains a CString and a bool.
If the CString is meant to be underlined then bool is true, else it is false.
I want to output the text in the vector to the screen making sure that text is underlined in the correct places.
So far I have the following code:
void CEmergenceView::AppendText( CString msg ) {
int nBegin;
CRichEditCtrl &rec = GetRichEditCtrl();
nBegin = rec.GetTextLength();
rec.SetSel(nBegin, nBegin); // Select last character
rec.ReplaceSel(msg); // Append, move cursor to end of text
rec.SetSel(-1,0); // Remove Black selection bars
nBegin = rec.GetTextLength(); // Get New Length
rec.SetSel(nBegin,nBegin); // Cursor to End of new text
// Fix annoying "do you want to save your changes?" when program exits
GetDocument()->SetModifiedFlag(FALSE); // -Optional- (sometimes you want this)
}
int nEnd = 0;
// loop through start of text to end of text
for(int k = 0; k < groups.size(); k++) {
rEditCtrl.SetSel(nEnd, nEnd);
rEditCtrl.GetSelectionCharFormat(cf);
if(groups.at(k).second) {
if(!cf.dwEffects & !CFE_UNDERLINE) {
CRichEditView::OnCharUnderline();
}
}
else if(!groups.at(k).second) {
if(cf.dwEffects & CFE_UNDERLINE) {
CRichEditView::OnCharUnderline();
}
}
AppendText(groups.at(k).first);
nEnd = nEnd + (groups.at(k).first.GetLength());
}
However, this is not underlining at all....Can anyone tell me what I'm doing wrong?? Thanks!
I think you should implement the OnCharUnderline
Try to call yours own function instead of the default one:
You can get it from here:
void CMyRichEditView::OnCharUnderline ()
{
CHARFORMAT2 cf;
cf = GetCharFormatSelection();
if (!(cf.dwMask & CFM_UNDERLINE) || !(cf.dwEffects & CFE_UNDERLINE))
cf.dwEffects = CFE_UNDERLINE;
else
cf.dwEffects = 0;
cf.dwMask = CFM_UNDERLINE;
SetCharFormat(cf);
}

c++ cli comparing hexadecimal bytes from a file not working

I have this file called ab.exe it contains this in hexadecimal
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BBAAE8CAFDFFFF83C408000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000054AAE8CAFDFFFF83C40800000000000000000000000000000000000000000000000000000000000000000000000000AAE8CAFDFFFF83C4088D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
I have this code in c++ that is suppose to detect if a string of hexadecimal is in a file or not and if it is add it to the list box.
array<Byte>^ target1 = { 0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08,0x8D };
array<Byte>^ target2 = { 0x54,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };
array<Byte>^ target3 = { 0xBB,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };
int matched1 = 0;
int matched2 = 0;
int matched3 = 0;
FileStream^ fs2 = gcnew FileStream(line, FileMode::Open, FileAccess::Read, FileShare::ReadWrite);
int value;
do
{
value = fs2->ReadByte();
if (value == target1[matched1]) {
matched1++;
}
else
matched1 = 0;
if (value == target2[matched2]) {
matched2++;
}
else
matched2 = 0;
if (value == target3[matched3]) {
matched3++;
}
else
matched3 = 0;
if(matched1 == target1->Length)
{
listBox1->Items->Add(line + "1");
}
if(matched2 == target2->Length)
{
listBox1->Items->Add(line + "2");
}
if(matched3 == target3->Length)
{
listBox1->Items->Add(line + "3");
}
} while (value != -1);
fs2->Close();
the problem is that it only adds line + 3 to the list box and not line + 1 or line + 2 to the list box
I do not know why that is because all 3 of the strings are in the file so they all should be added to the list box. for some reason only the last one is being added because I tried just having 2 and the second one got added.can someone show me why they are not all being added to the list box.
thanks
Update1
after playing around with it some more it is not the last target that gets added each time, It is the first string that appears in the file that gets added. I stepped through the program using message boxes and what is happening is lets say 54AAE8CAFDFFFF83C408 is the first string to appear in the file then line + 2 will be added, but then for some reason the matched integer for all 3 stop counting they just = 0 the rest of the file. can someone explain to me why that is and how to fix it.
Update2
here is the answer to the problem. all I needed to do was just add a matched = 0; after each add to list box command.
listBox1->Items->Add(line + "1");
matched1 = 0;
listBox1->Items->Add(line + "2");
matched2 = 0;
listBox1->Items->Add(line + "3");
matched3 = 0;
It seems to me that after the first matching of one pattern (here target3) you read beyond last byte of target3 (because of matched3++), this may cause undesired behavior.
Update1:
if(matched1 == target1->Length)
{
matched1 = 0; // pattern matched so reset counter
...
}