Reputation: 1267
I am using an external C library (libsvm) from within C++. I insert the header file in my class header file using
extern "C"{
#include "svm.h"
}
This library contains a struct called svm_model. It also contains a function that given some input parameters it allocates (malloc) space for a struct svm_model and returns a pointer to it. The function is
svm_model *svm_train(input_parameters)
In my code (in C++) I create a variable in my class that is a struct svm_model pointer. In my header file I do
class myClass
{
public:
int do_something();
private:
struct svm_model *m_data;
}
Inside "do_something()" I have successfully called svm_train in the following way:
struct svm_model *test = svm_train(input_parameters);
But whenever I want to write the result into m_data, I get a segmentation_fault. This happens for
m_data = svm_train(input_parameters);
but also happens if I do
struct svm_model *test = svm_train(input_parameters);
m_data = test;
In fact, I noticed that even if I do
printf("hello: %p\n", m_data);
It also crashes. Therefore I suspect that there has to be a problem with using a pointer to a structure (which has been defined elsewhere) inside a class, although I have not found any hints anywhere. I tried initializing it to NULL in my class constructor, but does not change anything.
Any help is appreciated.
Upvotes: 1
Views: 821
Reputation: 1267
Well, just found the problem and it was indeed elsewhere than reported. What happened is that I had created an STL vector of myClass and was accessing the methods on the first element of such vector, even though I had not explicitly created it, i.e.:
std::vector<myClass> dummy;
dummy[0].do_something();
Given that everything was compiling properly I did not think that this part of the code could give a problem.
Thanks all for your help.
Upvotes: 0
Reputation: 1777
The file svm.h already has the
extern "C" {
declaration. So instead of:
extern "C"{
#include "svm.h"
}
simply do:
#include "svm.h"
Also there is no need to repeat the struct key word again and again. So instead of:
struct svm_model *m_data;
do:
svm_model *m_data;
Upvotes: 1
Reputation: 1
If it crashes with simply
printf ("hello: %p\n", (void*)m_data);
then probably the issue is elsewhere and before. It looks like when you call that printf
function this
is invalid (perhaps NULL
?) or your memory heap is in very bad shape.
On Linux, I would suggest to compile with g++ -Wall -g
with a recent compiler (GCC 4.8 has just been released). Improve the code till no warnings are given. Then use gdb
and valgrind to debug it more.
You might want to also compile your libsvm
with debugging information and all warnings (or simply, use the debug variant of that package).
Upvotes: 6