Why does destructor cause segmentation fault? - destructor

All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
#ifndef BTree_H
#define BTree_H
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
template <typename T>
class BNode
{
public:
BNode();
BNode(int M);
~BNode();
int keyCount;
BNode *pointers;
T *keys;
};
template<typename T>
BNode<T>::BNode()
{
}
template<typename T>
BNode<T>::BNode(int M)
{
pointers = new BNode<T>[M];
keys = new T[M - 1];
}
template<typename T>
BNode<T>::~BNode()
{
delete[] pointers;
delete[] keys;
}
#endif
int main()
{
BNode<int> obj(5);
return 0;
}

You are deleting an array of pointers and keys, whereas you never defined these to be arrays.
Both of these are pointers.
You need to be freeing memory from the pointers, not arrays.
Try this:-
delete myPointer;
myPointer = NULL;
NOTE: If you're using C++, read about smart pointers. They'll come in handy!

Related

why my code which includes hashfunction and unordered_set uncompilable?

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
struct hashfunction{
size_t operator()(pair<string,int> x){
size_t ret=5381;
for(int i=0;i<x.first.length();i++){
ret=(ret<<5)+(ret)+x.first[i];
}
ret+=x.second;
return ret;
}
};
unordered_set<pair<string,int>,hashfunction> myset;
int main(void)
{
string a="123";
int b= 4;
myset.insert({a,b});
}
I am studying unordered_set and hashfunction. But the code above is not compilable. why not? Anyone can explain why it is not compilable and how to solve this problem?
const is needed after operator()(pair<string,int> x).

smart pointer to manage socket file descriptor

A smart pointer clears the memory if the pointer gets out of scope. I wanted to adapt this to a file descriptor, like a socket. There you need a user defined deleter, because close() is the function to free the file descriptor (fd) resources.
I found this useful page, unfortunately, most approaches did not work for me. Below is a working solution I found up to now, which is a little nasty. Because uniqu_ptr expects a pointer I created int *fd to store the fd value, therefore, I had to close(*fd) and delete fd in my custom deleter.
(1) Is there a better way?
Options A and B, which are based on the hints provided by the mentioned web page, are much nicer but causing odd compiler errors.
(2) Does anyone know how to correctly use these alternatives?
I'm using Qt Creator 3.0.1 with CONFIG += c++11 option and gcc version 4.8.2
#include "ccommhandler.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <qdebug.h>
//for Option A and B
struct CloseHandleDeleter {
typedef int pointer;
void operator()(int handle) const
{
}
};
//custom deleter, working
class MyComplexDeleter
{
public:
MyComplexDeleter() {}
void operator()(int* ptr) const
{
qDebug() << "Deleting ";
close(*ptr);
delete ptr;
}
};
CCommHandler::CCommHandler()
{
//Option A doesn't work
//std::unique_ptr<int, CloseHandleDeleter> file( socket(AF_INET, SOCK_STREAM, 0) );
//Option B doesn't work
//std::unique_ptr<int, int()(int)> filePtr( socket(AF_INET, SOCK_STREAM, 0) , close);
MyComplexDeleter deleter;
int *fd = new int;
*fd = socket(AF_INET, SOCK_STREAM, 0);
std::unique_ptr<int, MyComplexDeleter> p( fd , deleter);
}
Edit:
The posted answer by Nevin is right, it solves my initial problem.
The comment of learnvst caused to rethink my problem, and I have to say I may made it much more complex than needed, because the following simple class should also solve my problem of auto-free the memory of a resource or as in my case, to close the file descriptor:
class SocketHandler
{
int _fd;
public:
SocketHandler(int FD):_fd(FD){}
~SocketHandler() { if(_fd!=-1) close(_fd); }
operator int() const { return _fd; }
};
Because fd isn't a pointer, I wouldn't try to pigeonhole it into unique_ptr. Instead, create a custom class whose interface is based on unique_ptr, as in (caution: totally untested):
class unique_fd
{
public:
constexpr unique_fd() noexcept = default;
explicit unique_fd(int fd) noexcept : fd_(fd) {}
unique_fd(unique_fd&& u) noexcept : fd_(u.fd_) { u.fd_ = -1; }
~unique_fd() { if (-1 != fd_) ::close(fd_); }
unique_fd& operator=(unique_fd&& u) noexcept { reset(u.release()); return *this; }
int get() const noexcept { return fd_; }
operator int() const noexcept { return fd_; }
int release() noexcept { int fd = fd_; fd_ = -1; return fd; }
void reset(int fd = -1) noexcept { unique_fd(fd).swap(*this); }
void swap(unique_fd& u) noexcept { std::swap(fd_, u.fd_); }
unique_fd(const unique_fd&) = delete;
unique_fd& operator=(const unique_fd&) = delete;
// in the global namespace to override ::close(int)
friend int close(unique_fd& u) noexcept { int closed = ::close(u.fd_); u.fd_ = -1; return closed; }
private:
int fd_ = -1;
};

Compile error with boost bind in std::find_if

Consider this snippet:
#include <vector>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
template<typename PODType>
class SomeClass
{
public:
SomeClass() : m_pred(boost::bind(&SomeClass<PODType>::someMethodA, this, _1))
{
}
bool someMethodA(const PODType& elem)
{
return false;
}
bool someMethodB(const std::vector<PODType>& vec)
{
return (std::find_if(vec.begin(), vec.end(), m_pred(_1)) != vec.end());
}
private:
boost::function<bool(PODType)> m_pred;
};
int main(int argc, char* argv[])
{
SomeClass<int> obj;
std::vector<int> v;
obj.someMethodB(v);
return 0;
}
The compiler gives
error: no match for call to '(boost::function<bool(int)>) (boost::arg<1>&)'
note: no known conversion for argument 1 from 'boost::arg<1>' to 'int'
for the line return (std::find_if(vec.begin(), vec.end(), m_pred(_1)));
I'm trying to call someMethodA within the member predicate for the find_if calls.
Just pass m_pred, no need for m_pred(_1).

how to call a function of c++ file in .m file?

I have a header file test.h
#ifndef __visibilty_test__test__
#define __visibilty_test__test__
#include <iostream>
using namespace std;
class test{
public:
void print(string s);
};
#endif
and test.mm
#include "test.h"
using namespace std;
void test:: print(string s){
cout << s << endl;
}
now I want to call print function in my AppDelegate.m file in an iOS Application. Can anyone help me?
Thanks in advance
Rename AppDelegate.m to AppDelegate.mm.
Call the method as you would in C++:
test t;
t.print("Hello");
Your object:
#include <iostream>
using namespace std;
class test
{
public:
void print(string s)
{
cout << s << endl;
}
};
call from mm file
test *t = new test;
t->print("hello");

LLVM: "Export" class

I'd like to call this code from my program using LLVM:
#include <string>
#include <iostream>
extern "C" void hello() {
std::cout << "hello" << std::endl;
}
class Hello {
public:
Hello() {
std::cout <<"Hello::Hello()" << std::endl;
};
int hello() {
std::cout<< "Hello::hello()" << std::endl;
return 99;
};
};
I compiled this code to llvm byte code using clang++ -emit-llvm -c -o hello.bc hello.cpp and then I want to call it from this program:
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/IRReader.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
using namespace llvm;
void callFunction(string file, string function) {
InitializeNativeTarget();
LLVMContext context;
string error;
MemoryBuffer* buff = MemoryBuffer::getFile(file);
assert(buff);
Module* m = getLazyBitcodeModule(buff, context, &error);
ExecutionEngine* engine = ExecutionEngine::create(m);
Function* func = m->getFunction(function);
vector<GenericValue> args(0);
engine->runFunction(func, args);
func = m->getFunction("Hello::Hello");
engine->runFunction(func, args);
}
int main() {
callFunction("hello.bc", "hello");
}
(compiled using g++ -g main.cpp 'llvm-config --cppflags --ldflags --libs core jit native bitreader')
I can call the hello() function without any problems.
My question is: how can I create a new instance of the Hello class using LLVM?
I'm getting a segmentation fault when I call Hello::Hello()
Thanks for any hints!!
Manuel
Running clang++ -emit-llvm on the given source won't emit Hello::Hello, and m->getFunction("Hello::Hello") wouldn't find it even if it were emitted. I would guess it's crashing because func is null.
Trying to directly call functions which aren't extern "C" from the LLVM JIT is generally not recommended... I'd suggest writing a wrapper like the following, and compiling it with clang (or using the clang API, depending on what you're doing):
extern "C" Hello* Hello_construct() {
return new Hello;
}