c++ strange Segmentation fault appears - c++

Description
SFDD and Manager are classes that I created myself, following is my test file for testing class SFDD. (You can skip them and check the my test results)
#include <iostream>
#include <string>
#include "SFDD.h"
int main(int argc, char** argv) {
vector<int> vars_order;
int var_no = 18;
for (int i = 1; i <= var_no; ++i) vars_order.push_back(i);
Vtree* v = new Vtree(1, var_no*2-1, vars_order);
v->save_file_as_dot("vtree");
Manager m(v);
SFDD sfdd1 = m.sfddZero(); // create a SFDD representing Zero
SFDD sfdd2 = m.sfddOne();
SFDD sfdd3 = m.sfddVar(3);
SFDD sfdd4 = m.sfddVar(11);
SFDD sfdd6 = sfdd3.And(sfdd4, m, true);
sfdd6.save_file_as_dot("f=x11_and_x3"); // export sfdd6
cout << "Haha 1" << endl; // flag 1: for debugging
SFDD sfdd8 = sfdd4.Xor(sfdd6, m, true);
sfdd8.save_file_as_dot("f=x11_xor_(x11_and_x3)");
cout << "Haha 2" << endl; // flag 2: for debugging
sfdd3.Xor(sfdd8, m, true).save_file_as_dot("f=x3_xor_x11_xor_(x11_and_x3)");
cout << "Haha 3" << endl; // flag 3: for debugging
return 0;
}
After make and run. I got
Haha 1
Haha 2
Haha 3
which means it works. (execute to the end)
1. Segmentation fault 1
After I comment this line
sfdd6.save_file_as_dot("f=x11_and_x3"); // export sfdd6
I make and run again, I got
Haha 1
Segmentation fault (core dumped)
This comfuses me, because the function save_file_as_dot(string s) is just to export class SFDD to a dot file (dot is a language drawing simple graphs), I think it shouldn't be able to avoid a segmentation fault.
2. Segmentation fault 2
After I comment this line (uncomment above line this time)
SFDD sfdd1 = m.sfddZero(); // create a SFDD
I got
Haha 1
Haha 2
Segmentation fault (core dumped)
This comfuses me again, because last several lines don't use object sfdd1, why commenting this line avoids sementation fault?
Why do these segmentation faults appear? All I need are some clues or directions to solve these. Thank you.

You should be aware of the concept of Undefined Behavior, in your circumstances it's pretty safe to assume that your code invokes such behavior at some point and it sometimes causes the program to abruptly terminate due to a segmentation fault and sometimes it just doesn't.
To solve this problem, you need a tool like valgrind. Using this tool or it's equivalent for your OS and environment, you should be able to find the exact place where the violation occurs and solve the apparently random segmentation fault that appears and disappears depending on parts of the code that do not have any relation to the real problem.

Related

Calling a Tensorflow model in C++: "output depth must be evenly divisible by number of groups"

I'm using CppFlow to read and run a saved Tensorflow model in a C++ code. It should read in a jpeg image and a model, run the model on the image and give back an image of the same size and shape, following this example.
Here is my code:
#include <iostream>
#include "cppflow/ops.h"
#include "cppflow/model.h"
int main() {
auto input = cppflow::decode_jpeg(cppflow::read_file(std::string(IMAGE_PATH)));
input = cppflow::cast(input, TF_UINT8, TF_FLOAT);
cppflow::model model(std::string(MODEL_PATH));
auto output = model({{"serving_default_input0:0", input}}, {"StatefulPartitionedCall:0"});
std::cout << output << std::endl;
return 0;
}
But I'm getting an error:
2022-10-13 11:52:16.581298: F ./tensorflow/core/util/tensor_format.h:427] Check failed: index >= 0 && index < num_total_dims Invalid index from the dimension: 3, 0, C
Aborted (core dumped)
The example I'm following isn't great at explaining why it does things, so I already had to add the casting to a float in response to an error when it was not stated that my input had to be a float in the documentation. Since this error talks about incorrect dimensions I tried adding the line
input = cppflow::expand_dims(input, 0);
from the example but I don't know why I would need to do that and it still has an error:
terminate called after throwing an instance of 'std::runtime_error'
what(): output depth must be evenly divisible by number of groups: 64 vs 3
[[{{node StatefulPartitionedCall/StatefulPartitionedCall/model/relu2/Relu}}]]
Aborted (core dumped)
I don't know much about machine learning (it isn't my model, I'm just helping run it in C++) so if someone could please explain why you might do the expand_dims and what the resulting error means that would be really helpful.

Program received signal SIGSEGV, Segmentation fault while debugging in codeblocks

I'm a beginner in c++ and I was trying to solve https://projecteuler.net/problem=9 . I wrote a code for it and it shows the error - Program received signal SIGSEGV, Segmentation fault.
In strcmp () (C:\Windows\syswow64\msvcrt.dll)
while debugging.
If I straightaway run the program, a dialog box appears that says "windows is checking for a solution."
I've tried not using the string function and instead of writing pytha(a,b,c)=="true" , I just wrote axa+bxb=c*c (I wrote * instead of x but here it is not showing * between the two a's so I am replacing it with x) and the code works perfectly fine. But the thing is why does it not work with the string function?
I do not see anything wrong with the code.
I've found plenty of similar questions-
1. https://www.codeproject.com/Questions/93770/what-is-this-means-Program-received-signal-SIGSEGV
According to this one, my program is referring to a memory location which it does not have access to. But I do not see anything that is restricting this code to access something.
Program received signal SIGSEGV, Segmentation fault error
3.Debug---Program received signal SIGSEGV, Segmentation fault
program received signal SIGSEGV, segmentation fault
"Program received signal SIGSEGV, Segmentation fault."
Program received signal SIGSEGV, Segmentation fault
Program received signal SIGSEGV, segmentation fault, Linked list program
None of them answer my query as I am not able to relate to the codes mentioned in them to my code.
The link numbered 5 mentions that probably the error is because of the large number of computations involved. Even I had that doubt for my code, but it works fine when I don't use the function "pytha". Also, I do not see the large number of steps involved related in any way to an error related to memory access.
Also, even if large number of steps are involved is the reason, the program should compile when given enough time. But it doesn't. It straightaway shows the error that "Windows is looking for a solution."
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
string pytha(int a, int b, int c) {
if(a * a + b * b == c * c) return "true";
}
int main() {
for(int a = 1; a < 1000; a++) {
for(int b = 1; b < 1000; b++) {
for(int c = 1; c < 1000; c++) {
if(a + b + c == 1000) {
if(pytha(a, b, c) == "true")
cout << "a= " << a << " b= " << b << " c= " << c;
}
}
}
}
}
Please note that this code is a very inefficient one. The point is not to solve the question but to know why is the program not compiling.
pytha doesn't return a value on its all control flow paths.
Fix:
string pytha(int a, int b, int c)
{
if (a*a+b*b==c*c)
return "true";
return "";
}
Always compile your code with warnings enabled. For gcc and clang the compiler command line options are -Wall -Wextra -Werror.
You probably want to use bool type instead of string.

Segmentation fault disappears when debugging with GDB

I am having a segmentation fault while running this code: http://ideone.com/yU80Bd
The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in gdb with no segfault but running every other place with a segmentation fault?
Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE
The problem is that your input includes characters that are not in the range [a-Z]. For example: ! That causes the vector to be accesed at invalid indexes.
You can check these things running your program with valgrind.
valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830== at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830== at 0x401120: main (ideone.cpp:53)
The problem is in these lines:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}
c - 97 may be lower than 0.
You can check, for example:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
if (c < 'a' || c > 'z') continue;
++(cipherF[c-97].frequency);
}

Mysterious segmentation fault in C++?

I have been searching all over and cannot find anything like this. Now, I won't bore you with my whole program. It's incredibly long. But, here's your basic overview:
int main()
{
int i=0;
int h=5;
cout << "h(IS) = " << h << endl;
cout << "testing comment.";
while(i < 10)
{
cout << "I'm in the loop!";
i++;
}
return 0;
}
Looks great, right? Okay, so here's the problem. I run it, and I get a segmentation fault. The weirdest part is where I'm getting it. That testing comment doesn't even print. Oh, and if I comment out all the lines before the loop, I still get the fault.
So, here's my output, so you understand:
h(IS) = 5
Segmentation fault
I am completely, and utterly, perplexed. In my program, h calls a function - but commenting out both the line that prints h and the function call have no effect, in fact, all it does is give the segmentation fault where the line ABOVE the printing h line used to be.
What is causing this fault? Anything I can do to test where it's coming from?
Keep your answers simple please, I'm only a beginner compared to most people here :)
Note: I can provide my full code upon request, but it's 600 lines long.
EDIT: I have pasted the real code here: http://pastebin.com/FGNbQ2Ka
Forgive the weird comments all over the place - and the arrays. It's a school assignment and we have to use them, not pointers. The goal is to print out solutions to the 15-Puzzle. And it's 1 AM, so I'm not going to fix my annoyed comments throughout the thing.
I most recently got irritated and commented out the whole first printing just because I thought it was something in there...but no...it's not. I still get the fault. Just with nothing printed.
For those interested, my input information is 0 6 2 4 1 10 3 7 5 9 14 8 13 15 11 12
THANK YOU SO MUCH, EVERYONE WHO'S HELPING! :)
You slip over array boundaries, causing the corruption:
for (i=0; i<=4; i++)
{
for (j=0; j<=4; j++)
{
if (cur[i][j] == 0)
{
row = i;
col = j;
}
}
}
Your i and j indices must not reach 4.
valgrind is a great tool for debugging memory access problems. It's very easy to use on Linux. Just install G++ and valgrind, and then run (without the $ signs):
$ g++ -g -o prog prog.cpp
$ valgrind ./prog
It will print very detailed error messages about memory access problems, with source code line numbers. If those still don't make sense to you, please post the full source code (prog.cpp) and the full output of valgrind.
I've run valgrind for you, its output is here: http://pastebin.com/J13dSCjw
It seems that you use some values which you don't initialize:
==21408== Conditional jump or move depends on uninitialised value(s)
==21408== at 0x8048E9E: main (prog.cpp:61)
...
==21408== Conditional jump or move depends on uninitialised value(s)
==21408== at 0x804A809: zero(int (*) [4], int (*) [4], int*, int, int, int, int, int, int) (prog.cpp:410)
==21408== by 0x804A609: lowest(int (*) [4], int (*) [4], int, int, int, int, int, int) (prog.cpp:354)
==21408== by 0x804932C: main (prog.cpp:125)
...
To fix these problems, add code which initializes the variables depicted in the error lines above (e.g. line 61, 410), then recompile, and rerun with valgrind again, until all errors disappear.
If your program behaves weirdly even after fixing all problems reported by valgrind, please let us know.
Lines 57 - 67:
for (i=0; i<=4; i++)
{
for (j=0; j<=4; j++)
{
if (cur[i][j] == 0)
{
row = i;
col = j;
}
}
}
at least one of your errors is in this code, cur is declared int cur[4][4]; this means then when j==4 (and when i==4) you are not within the bounds of your array (well you are within the memory for some of them, but not all) valid values will be 0 - 3.

segmentation fault when ENTERING loop

I have a seg fault in C++ when entering a for loop. But I mean when ENTERING IT. Here is the code I'm running:
std::cout<<"forcing order"<<endl;
std::cout<<"crossoverPointNumber = "<<crossoverPointNumber<<endl;
for (long j=0; j<crossoverPointNumber; j++)
{
std::cout<<"j = "<<j<<". ";
offsprings[1][positionsInParent1[j]] = valuesInParent2[j]; // Forces the order
}//end for j
The output I get on the terminal is:
forcing order
crossoverPointNumber = 4
Segmentation fault
Can anyone explain to me what am I missing here?? it seems to be either very elementary or very complex C++ stuff...
You aren't adding an endl to the cout stream in your loop, so the code you've posted doesn't tell us when you are getting the segmentation fault. Until you add an endl the output stream won't be flushed.
I would strongly suspect that you are running off the end of your positionsInParent1 or valuesInParent2 arrays.