Boost test setup error: memory access violation - c++

I am getting the above error while running the executable after compiling and running the following file.
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/filesystem/fstream.hpp>
#include "index/DatabaseGroup.hpp"
using namespace boost::unit_test;
namespace indexing {
class ForwardDBTest {
/// A pointer to the database group object.
DatabaseGroup& databaseGroup;
std::string databaseName;
public:
~ForwardDBTest() {
}
;
ForwardDBTest(DatabaseGroup& databaseGroup_, std::string dbName) :
databaseGroup(databaseGroup_), databaseName(dbName) {
}
void boostTestCreateDB() {
databaseGroup.createDatabase(databaseName, databaseName);
}
};
class testSuites: public test_suite {
public:
testSuites() :
test_suite("test_suite") {
std::string db_location = "home/girijag/ripe/ripe_db";
std::cout << "hello" << std::endl;
int concurrency = 0;
std::string db_cache_policy = "AllMem";
boost::shared_ptr<DatabaseGroup> db = boost::shared_ptr<DatabaseGroup>(
new DatabaseGroup(db_location, concurrency, db_cache_policy));
std::string dbName = "DB1";
boost::shared_ptr<ForwardDBTest> instance(
new ForwardDBTest(*db, dbName));
test_case* boostTestCreateDB_test_case = BOOST_CLASS_TEST_CASE(
&ForwardDBTest::boostTestCreateDB, instance);
add(boostTestCreateDB_test_case);
}
~testSuites() {
}
;
};
test_suite* init_unit_test_suite(int argc, char** argv) {
test_suite* suite(BOOST_TEST_SUITE("Master Suite"));
suite->add(new testSuites());
return suite;
}
}'
Please let me know how should i resolve this?
i am getting errors as below:-
Test setup error: memory access violation at address: 0x00000021: no mapping at fault address
I have been struggling from past 2 days to figure out whats my issue

There are a number of disturbing things in the code, and some formatting seems have to been lost when posting the question, otherwise there is no chance it compiles. (For example, }’ ?!)
For starters, you shouldn’t place init_unit_test_suite(int, char**) in the indexing namespace, and subsequently there is no point in defining BOOST_TEST_MAIN - you will end up with multiple definition of the said init_unit_test_suite(int, char**) method.
In your case, the suite should be simply registered in the master test suite, there is no need to return a pointer to it from the method.
Here’s a minimal example that you can work with an extend for your purpose. It follows your structure, but omits non-relevant details:
#include <boost/test/included/unit_test.hpp>
#include <iostream>
using namespace boost::unit_test;
namespace indexing {
class ForwardDBTest {
public:
void boostTestCreateDB() { std::cout << __FUNCTION__ << std::endl; }
};
class TestSuite : public test_suite {
public:
TestSuite() : test_suite("test_suite") {
boost::shared_ptr<ForwardDBTest> instance(new ForwardDBTest);
add(BOOST_CLASS_TEST_CASE(&ForwardDBTest::boostTestCreateDB, instance));
}
};
} // namespace indexing
test_suite* init_unit_test_suite(int, char**) {
framework::master_test_suite().add(new indexing::TestSuite);
return 0;
}
/* Output:
Running 1 test case...
boostTestCreateDB
*** No errors detected
*/

Related

In function int main(): class name was not declared in this scope

Im using vscode and im new to c++. I learned how to create a header file link to its cpp and use it to main.cpp. The only problem bugs me out is why it causes an error this is my simple code.
Name.h
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
Name.cpp
#include "Name.h"
void myname::setname(std::string name)
{
Name = name;
}
void myname::prname()
{
std::cout<<"Hello :"<<Name<<std::endl;
}
Maiin.cpp
#include <iostream>
#include <string>
#include "Name.h"
using std::cout;
using std::string;
using std::endl;
int main()
{
myname Epoy; // IN FUNCTION INT MAIN: ERROR myname was not declared in this scope
Epoy.setname("Jomar"); //note myname <-rename "BUT THIS IS NOT THE ERROR CAUSE THIS JUST HAPPEN BECAUSE OF THE ERROR ABOVE "
Epoy.prname();
return 0;
}
also i tried so many method i even compiled this by using g++ Maiin.cpp Name.cpp - o Maiin
Still didnt work
Edit: Community want me to add more details.
What I asked was, have you write header guards in your header file: #ifndef Name_H, #define Name_H, #endif ? Since you use vscode you have to done it manually.
Like this:
#ifndef Name_H
#define Name_H
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
#endif
you missing a C++ constructor:
class Foo {
public:
Foo() { /* your init code */ } // <-- this is a std. C++ constructor
~Foo() { /* your clean-up code */ } // <-- this is a std. C++ de-structor
};
int main(int argc, char **argv) {
Foo bar; // here, you don't need the: ( ) object on heap !
}

C++ (14) - googletest undefined identifier

I'm using c++ 14. Why isn't googletest able to pick up the curl_client class object pointer? Did I initialize it correctly in CurlClientTest?
Testing code:
#include "../src/include/CurlClient.h"
#include <gtest/gtest.h>
#include <string>
class CurlClientTest : testing::Test {
public:
SimpleCURLClient::CurlClient *curl_client;
virtual void SetUp() {
curl_client = new SimpleCURLClient::CurlClient(test_url);
}
virtual void TearDown() {
delete curl_client;
}
private:
std::string test_url = "http://postman-echo.com/get?foo1=bar1&foo2=bar2";
};
TEST(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl << "\n";
}
code for CurlClient.h:
#include <curl/curl.h>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#ifndef UTILS_CURLCLIENT_H
#define UTILS_CURLCLIENT_H
namespace SimpleCURLClient {
class CurlClient {
public:
CurlClient(std::string remote_url, int ip_protocol = 1, int timeout = 10,
bool follow_redirects = 1);
~CurlClient();
void setCurlUrl(std::string &new_url);
std::string getCurlUrl();
void setOption(CURLoption curl_option_command, long curl_option_value);
void setOption(CURLoption curl_option_command, std::string curl_option_value);
void setHeader(std::vector<std::string> &header_list);
std::pair<CURLcode, std::string> makeRequest();
std::pair<CURLcode, std::string> makeRequest(std::string &post_params);
std::pair<CURLcode, std::string> sendGETRequest();
std::pair<CURLcode, std::string> sendPOSTRequest(std::string &post_params);
std::pair<CURLcode, std::string> sendDELETERequest(std::string &post_params);
private:
std::string m_curl_url;
CURL *m_curl;
struct curl_slist *m_curl_header_list;
};
} // namespace SimpleCURLClient
#endif // UTILS_CURLCLIENT_H
Error:
Build FAILED.
"E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj" (default target) (1) ->
(ClCompile target) ->
E:\somepath\simple_curl_cpp\test\CurlClientTest.cc(21): error C2065: 'curl_client': undeclared identifier [E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj]
E:\somepath\simple_curl_cpp\test\CurlClientTest.cc(21): error C2227: left of '->getCurlUrl' must point to class/struct/union/generic type [E:\somepath\simple_curl_cpp\build\test\simple_curl_cpp_test.vcxproj]
ANSWER (GIVEN BY Chris Olsen in comments) :
We have to use TEST_F and NOT TEST. Also change CurlClientTest to public. The below code for the test works.
#include "../src/include/CurlClient.h"
#include <gtest/gtest.h>
#include <string>
class CurlClientTest : public testing::Test {
public:
SimpleCURLClient::CurlClient *curl_client;
virtual void SetUp() {
curl_client = new SimpleCURLClient::CurlClient(test_url);
}
virtual void TearDown() {
delete curl_client;
}
private:
std::string test_url = "http://postman-echo.com/get?foo1=bar1&foo2=bar2";
};
TEST_F(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl() << "\n";
}
Tests using fixtures require use of the TEST_F macro. See Test Fixtures in the Google Test Primer for more info.
TEST_F(CurlClientTest, CurlClientInitTest) {
std::cout << curl_client->getCurlUrl << "\n";
}

How to use Clang LibTooling multiple times

Minimul source that use Clang LibTooling which is a very common way:
#include "pch.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "clang/Driver/Options.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include <iostream>
using namespace std;
using namespace clang;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
class ExampleVisitor : public RecursiveASTVisitor<ExampleVisitor> {
public:
explicit ExampleVisitor(CompilerInstance *CI) {}
};
class ExampleASTConsumer : public ASTConsumer {
private:
CompilerInstance *CI;
public:
explicit ExampleASTConsumer(CompilerInstance *CI) : CI(CI) {}
virtual void HandleTranslationUnit(ASTContext &Context) {
ExampleVisitor(CI).TraverseDecl(Context.getTranslationUnitDecl());
}
};
class ExampleFrontendAction : public ASTFrontendAction {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
return std::unique_ptr<ASTConsumer>(new ExampleASTConsumer(&CI));
}
};
void run(int argc, const char **argv, llvm::cl::OptionCategory& tc) {
CommonOptionsParser op(argc, argv, tc);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
std::cout <<"getSourcePathList.size="<< op.getSourcePathList().size()<<"\n";
int result = Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
}
int main(int argc, const char **argv) {
llvm::cl::OptionCategory tc1("c1");
llvm::cl::OptionCategory tc2("c2");
llvm::cl::OptionCategory tc3("c3");
run(argc, argv,tc1);
run(argc, argv,tc2);
run(argc, argv,tc3);
std::cin.get();
return 0;
}
the parameters to debug the application is:
"the_only_source_file_to_scan.cpp" --
which is fine.
The output is (from the method "run" above main()):
getSourcePathList.size=1
getSourcePathList.size=2
getSourcePathList.size=3
The problem is that main() calls run() 3 times with the same above parameter which contains only 1 source file to scan, but each time the size of the source-to-scan list stored in CommonOptionsParser increase by one (every item in the list is the same file input from argv), it just seems to append the source file to scan to the list each time.
Everything above is saved in newly created temporary variables in each run, then how and why does LibTooling keep states of the last run and how to "reset" these states?
use FixedCompilationDatabase could circumvent this problem, it can run multiple clangTool in one process
The above code use CommonOptionsParser, whose code is in
clang\lib\Tooling\CommonOptionsParser.cpp
in the method CommonOptionsParser::init there is:
static cl::list<std::string> SourcePaths(...);
Each invocation will add its sources to this static variable. So it is this local static variable that cause the memory of the previous invocations. In each invocation this local static variable is modified by cl::ParseCommandLineOptions in some unkown way since it is not passed into cl::ParseCommandLineOptions at all. After SourcePaths is modified (i.e. sources of the current invocation are added to SourcePaths which may already contain sources of previous invocations), it is finally copied into a instance variable.
BTW #AbaoZhang's clue helps me find the location, indeed CommonOptionsParser::init use FixedCompilationDatabase interally but not for the above situation.
static cl::list<std::string> SourcePaths(...);
#jw_ Yes This code makes problem.
You can fix this.
for (auto iter = llvm::cl::AllSubCommands->OptionsMap.begin(); iter != llvm::cl::AllSubCommands->OptionsMap.end(); iter++)
{
iter->getValue()->setDefault();
}
for (auto iter = llvm::cl::AllSubCommands->PositionalOpts.begin(); iter != llvm::cl::AllSubCommands->PositionalOpts.end(); iter++)
{
(*iter)->setDefault();
}
for (auto iter = llvm::cl::AllSubCommands->SinkOpts.begin(); iter != llvm::cl::AllSubCommands->SinkOpts.end(); iter++)
{
(*iter)->setDefault();
}

Cannot create a method in a class

I am new to c++ but have had some experience with java. I am trying to create a class but when i attempt to make a new method in the class I get several error (this is my .cpp file)
//.cpp file
#include "Test.h"
#include "Test.h"
#include <iostream>//unresolved inclusion
using namespace std;
void speak() {
if (happy) {//Symbol hapy could not be resolved
cout << "Meouw!" << endl;
} else {
cout << "Ssssss!" << endl;
}
}
void Test::makeHappy() { // member decleration not found
happy = true;//Symbol hapy could not be resolved
}
void Test::makeSad() { // member decleration not found
happy = false;//Symbol hapy could not be resolved
}
I dont get any errors in my heder file but have included it just in case
#ifndef TEST_H_
#define TEST_H_
class Test {
private:
bool happy;
public:
void makeHappy();
void makeSad();
void speak();
};
#endif /* TEST_H_ */
Finally I have another .cpp file I use which also gets errors
#include <iostream>//unresolved inclusion
#include "Test.h"
#include "Test.cpp"
using namespace std;
int main() {
Test jim;
jim.makeHappy();//method make happy could not be resolved
jim.speak();//method speak could not be resolved
Test bob;
bob.makeSad();//method make happy could not be resolved
bob.speak();//method speak could not be resolved
return 0;
}
This is the new error message I get when compiling
<!-- begin snippet: js hide: false -->
Sorry if this question is to open ended but I just cannot seem to find answers elsewhere.
this is your header file Test.h:
happy member was named bhappy_
for a private member think to add a getter and setter public member functions
#ifndef TEST_H_
#define TEST_H_
class Test {
private:
bool bhappy_;
public:
Test() // ctor
virtual ~Test() // dtor
public:
void makeHappy();
void makeSad();
void speak();
};
#endif /* TEST_H_ */
this is your Test.cpp file:
It's not advised to use using namespace std;
Don't include your header two times
//.cpp file
#include "Test.h"
#include <iostream>//unresolved inclusion
//ctor
Test::Test() : bhappy_(false)
{}
Test::~Test(){}
void Test::speak() {
if (bhappy_) {//Symbol hapy could not be resolved
std::cout << "Meouw!" << endl;
} else {
std::cout << "Ssssss!" << endl;
}
}
void Test::makeHappy() {
bhappy_ = true;//Symbol hapy could not be resolved
}
void Test::makeSad() { // member decleration not found
bhappy_ = false;//Symbol hapy could not be resolved
}
This is your main function:
#include "Test.h"
int main(int argc, char** argv) {
Test jim;
jim.makeHappy();//method make happy could not be resolved
jim.speak();//method speak could not be resolved
Test bob;
bob.makeSad();//method make happy could not be resolved
bob.speak();//method speak could not be resolved
return 0;
}
You need specify Test::speak().
Take should use this. to use class attribut. Think about getter and setter.
And finally, look C++ training, it should be usefull ^^ .
See you.

expected identifier before string constant

Having a program like this:
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){};
private:
std::string str;
};
class test1
{
public:
test tst_("Hi");
};
int main()
{
return 1;
}
…why am I getting the following when I execute
g++ main.cpp
main.cpp:16:12: error: expected identifier before string constant
main.cpp:16:12: error: expected ‘,’ or ‘...’ before string constant
You can not initialize tst_ where you declare it. This can only be done for static const primitive types. Instead you will need to have a constructor for class test1.
EDIT: below, you will see a working example I did in ideone.com. Note a few changes I did. First, it is better to have the constructor of test take a const reference to string to avoid copying. Second, if the program succeeds you should return 0 not 1 (with return 1 you get a runtime error in ideone).
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const std::string& s):str(s){};
private:
std::string str;
};
class test1
{
public:
test1() : tst_("Hi") {}
test tst_;
};
int main()
{
return 0;
}
There is another and more simplified way of doing what you want:Just change your statement from test tst_("Hi"); to test tst_{"Hi"}; and it will work. Below is the modified code and it works as expected.
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){cout<<"str is: "<<s;}
private:
std::string str;
};
class test1
{
public:
test tst_{"Hi"};
};
int main()
{ test1 obj;
return 0;
}
Note that i have just changed test tst_("Hi"); to test tst_{"Hi"}; and everything else is exactly the same. Just for confirmation that this works i have added one cout to check that it initialize the str variable correctly. I think this one line solution is more elegant(at least to me) and and up to date with the new standard.