String, debugging, and Segmentation Error goes hand in hand - c++

Hi I am doing this simple program
#include <iostream>
#include <string>
using namespace std;
int main (){
string hi("Hi how are you");
for(int i = 0;i<4;i++)
cout<<hi<<endl;
return 0;
}
When I compiled it and run it, there were no issues, but when I try to debug it, every time the IDE program (Code::Block 16.01) steps in or out of string hi("hi how are you") it gives me a Segmentation Fault.
I know SF is when the program tries to access a space of memory that it is not supposed to access, and I know string class is a C-Sytle string that allocates memory dynamically, and deletes them automatically when the program is finished, hence there should be no issue in memory management, so this code shouldn't be a problem.
BUT in this code I don't understand why do I get a SF when I debug it. When I tried debugging it for the first time and stepped out of hi, there were no errors, but when I tried watching hi, it gave me a SF, and when I try to debug it again, and I steped into string hi I get S.F.
Screenshot of the error FYI

When I was search information about this issue I found entry in Code::Blocks forum, but it is quite old.
However, there is possibility of bug in GDB for MiniGW. If you want to be sure, you should look for this issue and its fix.
I know that this isn't full answer, but you should go to this posts and read they, there is some solution:
Code::Blocks forum's posts:
1. Watching std::string in debugger causes segfault?!?
2. Still having seg fault while watching a string....

Related

GDB Skips While Loop Condition When Used With File Input

Alright Stack Overflow, I am running into a decently persistent problem in my C++ code. I'm sure this is one of those dumb mistake moments, but I have tried everything and cannot seem to squish this bug.
I have a bit of code here, and it's behavior is very odd. I have a main function that opens a file containing text I want to read in. I was taught in programming fundamentals class at my university that I could use getline() as a condition for the while loop, which is nice since it automatically terminates when it reaches the end of the file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input_mem_traces("gcc.txt");
string trace_to_parse = "";
while(getline(input_mem_traces, trace_to_parse))
{
cout << trace_to_parse << endl;
}
}
When I compile and run it, it works just fine. It reads out every single line of the file I pass it, and returns with no problems.
However, when I try to use gdb, and set a breakpoint at the line
cout << trace_to_parse << endl;
it didn't hit the breakpoint. Curious as to why that was, I broke above the loop, and tried single stepping through the code. When I got to the while loop, and tried to step, it simply skipped to the line after it, which happened to be the end of the program.
This behavior occurs both using the VSCode GUI front end for gdb, as well as straight gdb from the command line. I am running this on Windows using Ubuntu under WSL2, and VSCode as my IDE with the Remote - WSL extension enabled.
Turns out there was some weirdness going on with the working directory with GDB. For some reason, my working directory was changing under the VSCode GUI, thus the file was not able to be opened, and the while loop condition performed as expected for that circumstance by not entering the loop. Upon the recommendation by Retired Ninja in the comments, I used an absolute path in the fstream object constructor, and that solved the issue.

GDALDriver::Create GTiff Segmentation Fault

I am new to using GDAL, and am having trouble creating a GDALDataset using the GDALDriver::Create() method. In this case, I am using C++. Ultimately I am trying to create a raster and write values from an array to the raster. A minimal working example of the code that generates the problem of creating a dataset is given here:
#include <iostream>
#include </usr/include/gdal/gdal_priv.h>
int main(){
std::cout << "starting GDAL business\n";
const char *raster_format = "GTiff";
GDALDriver *g_driver;
g_driver = GetGDALDriverManager()->GetDriverByName(raster_format);
GDALDataset *g_dataset;
const char *test_file = "test_file.tif";
char **raster_creation_options = NULL;
std::cout << "raster options created\n";
g_dataset = g_driver->Create(test_file,
100,200,1,GDT_Float32,
raster_creation_options); //<--- seg faults
std::cout << "dataset created\n";
}
The resulting console looks like:
starting GDAL business
raster options created
Segmentation fault (core dumped)
I am just following the basic API tutorial (Link), but am encountering this problem. I am on Ubuntu 14.04, using the repository's libgdal packages.
Can anyone shed some light on this problem?
I know this is an old question and the issue has probably long since been resolved, but I figured I would throw my answer into the ring. After all, I was directed here when I had this problem and it seems like the question has a fair amount of views.
If your code is not working, and you are having trouble loading the driver, I would suggest adding the line GDALAllRegister();. I was following the same tutorial as you, and they mention adding this line at the top of the tutorial, but if you're like my and rushed right to the part you needed, the Create part of the tutorial, you probably overlooked that step.
Hopefully this answer helps someone, if not the original author of the question.

Why would calling MessageBox[etc]() without a return variable cause the program to crash?

So if I write the following code:
MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
the program crashes with an access violation when it exits. When I write the code like this:
int a;
a = MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
it doesn't crash. Now I know why it crashes when it crashes thanks to another question I asked, also regarding argument-mismatching, but I don't know why it crashes.
So why does this cause an APPCRASH? I was always under the impression that calling a function that had a return-type, without actually giving one was safe, example:
int SomeFunction (void) {
std::cout << "Hello ya'll!\n";
return 42;
}
int main (void) {
int a;
// "Correct" ?
a = SomeFunction();
a = MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
// "Incorrect" ?
SomeFunction();
MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
}
When I run this kind of test "clean" (in a new file) I don't get any errors. It only seems to give an error with MessageBox/MessageBoxA when run in my program. Knowing the possible causes would help me pinpoint the error as the project code is too big to post (and I would need my friend's permission to post his code anyway).
Additional Info:Compiler = GCCPlatform = Windows
EDIT:
UpdateThanks everyone for your feedback so far. So I decided to run it through a debugger... Now Code::Blocks doesn't debug a project unless it is loaded from a project file (*.cbp) - AFAIK. So I created an actual project and copy-pasted our project's main file into the projects. Then I ran in debug mode and didn't get so much as a warning. I then compiled in build mode and it ran fine.Next, I decided to open a new file in Dev-C++ and run it through the debugging and later the final build process and again I got no errors for either build or debug. I cannot reproduce this error in Dev-C++, even with our main file (as in the one that causes the error in Code::Blocks).
ConclusionThe fault must lie in Code::Blocks. AFAIK, they both use GCC so I am pretty confused. The only thing I can think of is a version difference or perhaps my compiler settings or something equally obscure. Could optimizer settings or any other compiler settings somehow cause this kind of error?
The version with the return value does not crash because it had one int more on the stack. Your erroneous code reads over the bounds of the stack and then runs into an access violation. But if you have more on the stack you will not hit the guard page, because that is just enough extra stack. If the the erroneous code only reads it is sort of OK, but still broken.
We had one bit of WTF inducing code that was like so:
char dummy[52];
some_function();
There was thankfully a longish comment explaining that removing dummy, makes some_function crash. It was in a very old application so nobody dared touch it and the some_function was totally different module we had no control over. Oh yea and that application was running smoothly in the field for over 20 years in industrial installations, like refineries or nuclear power plants... ^_^

Segmentation fault when different input is given

I do some image processing work in C++. For this i use CImg.h library which i feel is good for my work.
Here is small piece of code written by me which just reads an image and displays it.
#include "../CImg.h"
#include "iostream"
using namespace std;
using namespace cimg_library;
int main(int argc,char**argv)
{
CImg<unsigned char> img(argv[1]);
img.display();
return 0;
}
When i give lena.pgm as input this code it displays the image. Where as if i give some other image, for example ddnl.pgm which i present in the same directory i get "Segmentation Fault".
When i ran the code using gdb i get the output as follows:
Program received signal SIGSEGV, Segmentation fault.
0x009823a3 in strlen () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.9-2.i686 libX11-1.1.4-5.fc10.i386 libXau-1.0.4-1.fc10.i386 libXdmcp-1.0.2-6.fc10.i386 libgcc-4.3.2-7.i386 libstdc++-4.3.2-7.i386 libxcb-1.1.91-5.fc10.i386
Can some one please tell me what the problem is? and how to solve it.
Thank you all
Segfault comes when you are trying to access memrory which you are not allowed to access.
So please check that out in the code.
The code itself looks just fine. I can suggest some ways to go ahead with debugging -
Try removing the display() call. Does the problem still occur? (I'd assume it does).
Try finding out where in the CImg code is the strlen() that causes the segmentation fault (by using a debugger). This may give additional hints.
If it is in the PGM file processing, maybe the provided PGM file is invalid in some way, and the library doesn't do error detection - try opening it in some other viewer, and saving it again (as PGM). If the new one works, comparing the two may reveal something.
Once you have more information, more can be said.
EDIT -
Looking at the extra information you provided, and consulting the code itself, it appears that CImg is failing when trying to check what kind of file you are opening.
The relevant line of code is -
if (!cimg::strcmp(ftype,"pnm")) load_pnm(filename);
This is the first time 'ftype' is used, which brings me to the conclusion that it has an invalid value.
'ftype' is being given a value just a few lines above -
const char *const ftype = cimg::file_type(0,filename);
The file_type() function itself tries to guess what file to open based on its header, probably because opening it based on the extension - failed. There is only one sane way for it to return an invalid value, which would later cause strcmp() to fail - when it fails to identify the file as anything it is familiar with, it returns NULL (0, actually).
So, I reiterate my suggestion that you try to verify that this is indeed a valid file. I can't point you at any tools that are capable of opening/saving PGM files, but I'm guessing a simple Google search would help. Try to open the file and re-save it as PGM.
Another "fun to track down" cause of segmentation faults is compilier mismatches between libraries - this is especially prevalent when using C++ libraries.
Things to check are:
Are you compiling with the same compiler as was used to compile the CImg library?
Are you using the same compiler flags?
Were there any defines that were set when compiling the library that you're not setting now?
Each of these has bitten me in subtle ways before.

How to fix memory access error

I am working on a migration project, here we are migrating large set of C++ libraries from Mainframe to Solaris. We have complted migration sucessfully, but while running the application, some places it crashes with 'signal SEGV (no mapping at the fault address)'.
Since the application supports on windows also, we checked with purify on windows. There are no memory leaks in the application and it works fine on windows.
Can any one suggests, what could be the other reasons which may create this type of errors. Any tools for tracing this type of errors?
It's not necessarily a memory leak. It could be that a piece of memory is referenced after it is free'ed.
My friend once came to me with a piece of code that runs fine on Windows but gives segv on Linux. It turned out that sometimes the memory is still valid after you free'ed it on Windows (probably for a short period of time) but immediately triggered segv on Linux.
The line below looks wrong to me
m_BindMap[sLabel] = b; // crashes at this line at when map size
I assume you are trying to add a number to the end of the string. Try this instead
stringstream ss;
ss << ":BIND" << ns;
string sLabel = ss.str();
Are you using g++? If so, recompile with the "-g" flag. Run the program in gdb. When it crashes type "bt" (for backtrace) and that should tell you where your problem is.
I am using CC compiler on solaris and dbx debugger. I know the call stack where it is crashing. But it is abromal crash.
map<string,CDBBindParam,less<string> >m_BindMap;
CNumString ns(CNumStringTraits(0,2,'0'));
ns = m_BindMap.size();
string sLabel = ":BIND"+ns;
CDBBindParam b(sLabel,val);
**m_BindMap[sLabel] = b;** // crashes at this line at when map size is more than 2
return sLabel;