Segmentation fault when different input is given - c++

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.

Related

String, debugging, and Segmentation Error goes hand in hand

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....

libsndfile - sf_open(): Undefined references in time.h

I am using libsndfile and portaudio to play audio from a .wav file and I am getting some weird undefined reference (in time.h...?) errors upon use of sf_open(const char*, int, SF_INFO*) Before showing the errors, here is some basic info: I'm using MinGW 3.21 (cannot upgrade due to IDE constraints) on Windows 10, with CMake as my build system. I have verified that the const char* passed to sf_open is a valid file name and I have checked that no other lines of code are causing this compilation error. Without further ado, have some lovely errors:
libsndfile/lib/libsndfile.a(aiff.o): In function time':
c:/dwimperl/c/bin/../lib/gcc/i686-w64-mingw32
/4.4.7/../../../../i686-w64-mingw32/include/time.h:242:
undefined reference to _time32'
This is printed several times, probably because the function time is used a lot in sf_open although I haven't a clue as to why. This happens as well:
In function `gmtime':
c:/dwimperl/c/bin/../lib/gcc/i686-w64-
mingw32/4.4.7/../../../../i686-w64-mingw32/include/time.h:240:
undefined reference to `_gmtime32'
These errors imply no correlation between sf_open and time.h, but I even tried the following,
#include<sndfile.h>
int main {
sf_open(nullptr, 0, nullptr);
return 0;
}
and gotten the same result. I have libsndfile-1.dll in the same directory as my compiled binaries, and am linking to both libsndfile.a and libsndfile.dll.a. I have tried only linking to libsndfile.a with the same result. However, I tried linking only to libsndfile.dll.a and the program compiled but then crashed, saying:
An error occured while using the portaudio stream
Error number: -9984
Error message: Incompatible host API specific stream info
I'm not sure whether or not that is something for another question, but I thought I'd mention it, seeing that sf_open, the faulty function, seems to do something with stream info. Anyways, this is as far as I've gotten. Help is appreciated!
Look at me being such a genius, answering the question by asking it and then not noticing. Sometimes I wonder how I'm still alive. Anyways, it was simple. Don't link libsndfile.a, just libsndfile.dll.a. That's all. The PortAudio error was something entirely unrelated. Sorry for the idiocy, hope this helps at least one person...?

Running the executable of hdl_simple_viewer.cpp from Point Cloud Library

The Point Cloud library comes with an executable pcl_hdl_viewer_simple that I can run (./pcl_hdl_viewer_simple) without any extra arguments to get live data from a Velodyne LIDAR HDL32.
The source code for this program is supposed to be hdl_viewer_simple.cpp. A simplified version of the code is given on this page which cannot be compiled readily and requires a tiny bit of tweaking to make it compile.
My problem is that the executable that I build myself for both the versions are not able to run. I always get the smart pointer error "Assertion px!=0" error. I am not sure if I am not executing the program in the correct way or what. The executable is supposed to be executed like
./hdl_viewer_simple -calibrationFile hdl32calib.xml -pcapFile file.pcap
in case of playing from previously recorded PCAP files or just ./hdl_viewer_simple if wanting to get live data from the real sensor. However, I always get the assertion failed error.
Has anyone been able to run the executables? I do not want to use the ROS drivers
"Assertion px!=0" is occurring because your pointer is not initialized.
Now that being said, you could initialize it inside your routines, in case the pointer is NULL, especially for data input.
in here, you can try updating the line 83 like this :
CloudConstPtr cloud(new Cloud); //initializing your pointer
and hopefully, it will work.
Cheers,

How to get more info if lt_dlopen fails?

I'm calling lt_dlopen and getting a generic file not found error (translated errno text). How can I get more information about what is actually failing, as the file is definitely there.
This is a C++ program loading a C++ library. Otherwhere in the same program I use the same command to open other libraries without a problem, thus I fear it might be something specific to this library. I've used ldd and all those dependencies of the library are met.
I stumbled across something that kind of works:
export LD_DEBUG=all
And then proceed to sift throught the extreme mass of output. In this case I found a "lookup error" and one of the symbols could not be resolved. I'm not sure why, but that is perhaps not relevant to this question.
Recompile libtool with "-DLT_DEBUG_LOADERS" in $CFLAGS. Adjust LD_LIBRARY_PATH so that your program will find this debug libltdl.so instead of the system one. That debug version of ltdl will print explicit errors for each loader's attempt to open the target with much less verbosity than LD_DEBUG=all.
From http://www.delorie.com/gnu/docs/libtool/libtool_46.html :
Function: lt_dlhandle lt_dlopen (const char *filename)
[...] If lt_dlopen fails for any reason, it returns NULL.
Function: const char * lt_dlerror (void)
Return a human readable string describing the most recent error that
occurred from any of libltdl's functions. Return NULL if no errors
have occurred since initialization or since it was last called.

LoadLibrary fails when including a specific file during DLL build

I'm getting really strange behavior in one of the DLLs of my C++ app. It works and loads fine until I include a single file using #include in the main file of the DLL. I then get this error message:
Loading components from D:/Targets/bin/MatrixWorkset.dll
Could not load "D:/Targets/bin/MatrixWorkset.dll": Cannot load library MatrixWorkset: Invalid access to memory location.
Now I've searched and searched through the code and google and I can't figure out what is going on. Up till now everything was in a single DLL and I've decided to split it into two smaller ones. The file that causes the problems is part of the other second library (which loads fine).
Any ideas would really be appreciated.
Thanks,
Jaco
The likely cause is a global with class type. The constructor is run from DllMain(), and DllMain() in turn runs before LoadLibrary() returns. There are quite a few restrictions on what you can do until DllMain() has returned.
Is it possible that header includes a #pragma comment(lib,"somelibrary.lib") statement somewhere? If so it's automatically trying to import a library.
To troubleshoot this I'd start by looking at the binary with depends (http://www.dependencywalker.com/), to see if there are any DLL dependencies you don't expect. If you do find something and you are in Visual Studio, you should turn on "Show Progress" AKA /VERBOSE on the linker.
Since you are getting the Invalid Access to memory location, it's possible there's something in the DLLMAIN or some static initializer that is crashing. Can you simplify the MatrixWorkset.dll (assuming you wrote it)?
The error you describe sounds like a run-time error. Is this error displayed automatically by windows or is it one that your program emits?
I say attach a debugger to your application and trace where this error is coming from. Is Windows failing to load a dependency? Is your library somehow failing on load-up?
If you want to rule in/out this header file you're including, try pre-compiling your main source file both with and without this #include and diff the two results.
I'm still not getting it going. Let me answer some of the questions asked:
1) Windows is not failing to load a dependency, I think since Dependency Walker shows everything is ok.
2) I've attached a debugger which basically prints the following when it tries to load MatrixWorkset.dll:
10:04:19.234
stdout:&"warning: Loading components from D:/ScinericSoftware/VisualWorkspace/trunk/Targets/bin/MatrixWorkset.dll\n"
10:04:19.234
stdout:&"\n"
status:Stopped: "signal-received"
status:Stopped.
10:04:19.890
stdout:30*stopped,reason="signal-received",signal-name="SIGSEGV",signal-meaning="Segmentation fault",thread-id="1",frame={addr="0x7c919994",func="towlower",args=[],from="C:\\WINDOWS\\system32\\ntdll.dll"}
input:31info shared
input:32-stack-list-arguments 2 0 0
input:33-stack-list-locals 2
input:34-stack-list-frames
input:35-thread-list-ids
input:36-data-list-register-values x
10:04:19.890
3) MSalters: I'm not sure what you mean with a "global with class type". The file that is giving the problems have been included in a different DLL in which it worked fine and the DLL loaded successfully.
This is the top of the MatrixVariable.h file:
#include "QtSF/Variable.h" // Located in depending DLL (the DLL in which this file always lived.
#include "Matrix.h" // File located in this DLL
#include "QList" // These are all files from the Qt Framework
#include "QModelIndex"
#include "QItemSelection"
#include "QObject"
using namespace Zenautics;
using namespace std;
class MatrixVariable : public Variable
{
Q_OBJECT
Q_PROPERTY(int RowCount READ rowCount WRITE setRowCount)
Q_PROPERTY(int ColumnCount READ columnCount WRITE setColumnCount)
Q_PROPERTY(int UndoPoints READ undoPoints WRITE setUndoPoints)
public:
//! Default constructor.
MatrixVariable(const QString& name, int rows, int cols, double fill_real = 0, double fill_complex = 0, bool isReal = true);
etc. etc. etc.
A possible solution is to put the MatrixVariable file back in the original DLL but that defeats the whole idea of splitting the DLL into smaller parts which is not really a option.
I get that error from GetLastError() when I fail to load a DLL from a command line EXE recently. It used to work, then I added some MFC code to the DLL. Now all bets are off.
I just had this exact same problem. A dll that had been working just fine, suddenly stopped working. I was taking an access violation in the CRT stuff that initializes static objects. Doing a rebuild all did not fix the problem. But when I manually commented out all the statics, the linker complained about a corrupt file. Link again: Worked. Now I can LoadLibrary. Then, one by one, I added the statics back in. Each time, I recompiled and tested a LoadLibrary. Each time it worked fine. Eventually, all my statics were back, and things working normally.
If I had to guess, some intermediate file used by the linker was corrupted (I see the ilk files constantly getting corrupted by link.exe). If you can, maybe wipe out all your files and do a clean build? But I'm guessing you've already figured things out since this is 6 months old ...