C++ Linux string.h invalid read reported in valgrind - c++

The Linux program below builds a path by adding some strings to a filesystem path:
#include <filesystem>
int main(int, char**) {
//
std::cout << "Application STARTING\n";
//
fs::path path;
// Add to path
path /= "/media";
path /= "aaa";
path /= "bbb";
// path /= "ccc";
//
std::cout << path.c_str() << std::endl;
//
std::cout << "Application STOPPED\n";
}
If I run this file in valgrind, this is the output:
Application STARTING
/media/aaa/bbb
Application STOPPED
If I uncomment the line that adds "ccc" to the path, compile and run again in valgrind, I get this:
Application STARTING
==2231== Invalid read of size 1
==2231== at 0x4860214: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==2231== Address 0x4d25c17 is 0 bytes after a block of size 31 alloc'd
==2231== at 0x4848744: operator new(unsigned int) (vg_replace_malloc.c:282)
==2231== by 0x4A79CBB: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned int, unsigned int, char const*, unsigned int) (in /usr/lib/arm-linux-gnueabihf/libstdc++.so.6.0.28)
==2231==
/media/aaa/bbb/ccc
Application STOPPED
I am compiling with these settings:
/usr/bin/arm-linux-gnueabihf-g++ -I/usr/include/alsa -pthread -Wall -Wextra -pedantic -g -DTMTP_DEBUG -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp
Is this a valgrind error? Am I using the fs::path correctly?
_ UPDATE _
I have reduced to the minimum compiler settings:
/usr/bin/arm-linux-gnueabihf-g++ -g -std=gnu++17 -o CMakeFiles/tmtp.dir/main.cpp.o -c /media/ssd/projects/tmtp/code/main.cpp
I am compiling in C++17 because this allows me to use the non-experimental version of filesystem.
Bad memory read is still reported.
_ ANOTHER UPDATE _
I can create the invalid read error without using filesystem. The code below also reports an invalid read. There are two lines marked in the code, commenting out either removes the invalid read.
#include <iostream>
#include <string.h>
class CPath
{
public:
inline const char* c_str() const { return m_strPath.c_str(); }
inline void operator/=(const char* psz) { append(psz); }
public:
void append(const char* psz)
{
//
m_strPath += '/'; // <--- REMOVE TO PREVENT INVALID READ
m_strPath.append(psz);
}
private:
std::string m_strPath;
};
int main(int, char**) {
//
std::cout << "Application STARTING\n";
//
CPath path;
path /= "media";
path /= "aaa";
path /= "bbb";
path /= "ccc"; // <--- REMOVE TO PREVENT INVALID READ
//
std::cout << path.c_str() << std::endl;
//
std::cout << "Application STOPPED\n";
}

Related

C++ DevIL function ilLoadImage - program exit, access violation

I've got a path to my file defined this way:
const char* GROUND_TEXTURE_FILE = "objects/textures/grass.jpg";
And here is the function, which I use to load image:
bool loadTexImage2D(const string &fileName, GLenum target) {
...
// this will load image data to the currently bound image
// at first, we must convert fileName, for ascii, this method is fine?
wstring file(fileName.begin(), fileName.end());
if(ilLoadImage(file.c_str()) == IL_FALSE) { //here the program falls
What's wrong in my code? Why the program falls when ilLoadImage is called? I think, that file.c_str() should work fine as a wchar_t * type or not? Thanks for answer :)
As the author's said, you can do pretty anything without initializing the lib :D
#include <iostream>
#include <IL/il.h>
int main ()
{
std::string filename = "objects/textures/grass.jpg";
ilInit();
if (!ilLoadImage(filename.c_str())) {
std::cout << ilGetError() << std::endl;
return 1;
}
std::cout << ilGetInteger(IL_IMAGE_WIDTH) << std::endl;
std::cout << ilGetInteger(IL_IMAGE_HEIGHT) << std::endl;
return 0;
}
build:
g++ -Wall -pedantic --std=c++11 -g -o app main.cpp -lIL

Why tcmalloc don't print function name, which provided via dlopen

I have next some project:
main.cpp
#include <iostream>
#include <cstddef>
#include <dlfcn.h>
int main()
{
void* handle = dlopen("./shared_libs/libshared.so", RTLD_LAZY);
if (NULL == handle)
{
std::cerr << "Cannot open library: " << dlerror() << '\n';
return -1;
}
typedef int (*foo_t)(const std::size_t);
foo_t foo = reinterpret_cast<foo_t>(dlsym(handle, "foo"));
const char* dlsym_error = dlerror();
if (dlsym_error)
{
std::cerr << "Cannot load symbol 'foo': " << dlsym_error << '\n';
dlclose(handle);
return -2;
}
std::cout << "call foo" << std::endl;
foo(10);
dlclose(handle);
return 0;
}
shared.cpp:
#include <cstddef>
#include <iostream>
extern "C"
{
int foo(const std::size_t size)
{
int b = size / size;
int* a = new int[size];
std::cout << "leaky code here" << std::endl;
}
}
and Makefile:
all:
g++ -fPIC -g -c shared.cpp
g++ -shared -o shared_libs/libshared.so -g shared.o
g++ -L shared_libs/ -g main.cpp -ldl
I use tcmalloc for debug this test program, which load dynamically libshared.so:foo and execute it.run command:
LD_PRELOAD=/usr/local/lib/libtcmalloc.so HEAPCHECK=normal ./a.out
The 1 largest leaks:
Using local file ./a.out.
Leak of 40 bytes in 1 objects allocated from:
# 7fe3460bd9ba 0x00007fe3460bd9ba
# 400b43 main
# 7fe346c33ec5 __libc_start_main
# 400999 _start
# 0 _init
Why I get address 0x00007fe3460bd9ba instead of line in foo function?
please help
P.s. I tried to use gdb with LD_PRELOAD=.../tcmalloc.so, but I get:
"Someone is ptrace()ing us; will turn itself off Turning perftools heap leak checking off"
Try removing dlclose call.
It's known issue that heap checker & profilers can't handle unloaded
shared objects.

C++ error: undefined reference to function

I have three files:
Two .cpp files (Reader.cpp and algo.cpp) and one header file (algo.h).
In Reader.cpp file, its function PacketHandler calls a function present in algo.cpp.
Reader.cpp
void PacketHandler(Packet* sniff_packet, void* user) {
std::string payload;
RawLayer* raw_payload = sniff_packet->GetLayer<RawLayer>();
if (raw_payload) {
/* Summarize some data */
cout << "[+] ------- [+]" << endl;
TCP* tcp_layer = sniff_packet->GetLayer<TCP>();
cout << "[#] TCP packet from source port: " << dec << tcp_layer->GetSrcPort() << endl;
cout << "[#] With Payload: " << endl;
payload = raw_payload->GetStringPayload();
SPPM(payload); // Function present in algo.cpp
}
}
void main() { // }
algo.h
#ifndef algo_H_
#define algo_H_
#include <string>
using namespace std;
void SPPM (std::string input);
#endif
algo.cpp
#include "algo.h"
#define byte uint8_t
using namespace std;
void SPPM(std::string input){ //definition }
When I compile the code using g++, I get this error:
In function `PacketHandler(Crafter::Packet*, void*)':
/home/maleeha/libcrafter_latest/libcrafter-master/libcrafter/pcap_reader.cpp:32: undefined reference to `SPPM(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'collect2: ld returned 1 exit status
I am executing my code this way:
g++ -c Reader.cpp -o Reader.o -g -lcrafter
g++ -c algo.cpp -o algo.o
g++ -o program Reader.o algo.o -lcrafter
./program Packets.pcap
Why is this error coming?

Linker error compiling keyczar program

I am using g++ -lkeyczar -lcrypto -o basic_encrypt -Wall -O2 base_encrypt.cpp to compile the following code:
#include <cassert>
#include <iostream>
#include <string>
#include <keyczar/keyczar.h>
void EncryptAndDecrypt(const std::string& location) {
keyczar::Keyczar* crypter = keyczar::Crypter::Read(location);
if (!crypter)
return;
std::string input = "Secret message";
std::string ciphertext;
std::cout << "Plaintext: " << input << std::endl;
bool result = crypter->Encrypt(input, &ciphertext);
if (result) {
std::cout << "Ciphertext (Base64w): " << ciphertext << std::endl;
std::string decrypted_input;
bool result = crypter->Decrypt(ciphertext, &decrypted_input);
if (result)
assert(input == decrypted_input);
}
delete crypter;
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "An absolute key set location must be provided as argument"
<< std::endl;
return 1; // error
}
// The first argument must represent the keyset's location
const std::string location(argv[1]);
EncryptAndDecrypt(location);
return 0;
}
Which is a tutorial taken from here
However, I am running into the following error:
/tmp/ccNlack3.o: In function `EncryptAndDecrypt(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
base_encrypt.cpp:(.text+0xf): undefined reference to `keyczar::Crypter::Read(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: ld returned 1 exit status
I am unable to solve this since I know that I am already giving the library flags while compiling. Why is it still unable to link correctly ?
Put the library flags at the end of the command line:
g++ -o basic_encrypt -Wall -O2 base_encrypt.cpp -lkeyczar -lcrypto

Modify Code through a GUI

Hey this is more of a question, i want to know if it is possible to modify code through GUI asking because i was asked to see if i could create a GUI where the user can change certain attributes. i.e an exmaple is below
start %= -(status)
> lexeme[elementV]
> -(lexeme[elementF])
> +(inboundGroup);
Above is part of my code which is Boost SPIRIT which parses Strings so for example would it be possible to change the + to a * or - etc
+ = One
- = optional
* = multiple
Do you think it would be possible to change that through a GUI i think it could be just not sure on how to do it?
Any help i will be very grateful
Thanks Shamari
Everything is possible in programming ;-)
For dynamic modification of a program during execution, there are several solutions :
Use a dynamic language like LUA
Use a plugin system with dynamic loading
Since you require C++ and Boost Spirit, I think the best solution is to generate a plugin on the fly and load it afterwards.
Your program will generate code, compile it into a shared library (.so) and then load and execute it. (Some people will find that dirty. It's insecure also. But it's simple and it works.)
Here is an exemple for linux : plugin.h :
#ifndef PLUGIN_H__
#define PLUGIN_H__
#ifdef __cplusplus
extern "C" {
#endif
int process();
typedef int (*plugin_process_fn_ptr)();
#ifdef __cplusplus
}
#endif
#endif // PLUGIN_H__
Note that we must use extern C or else, C++ name mangling will make it difficult to import symbols.
plugin.cpp :
#include "plugin.h"
#include <iostream>
using namespace std;
int process()
{
int return_value = 0;
#include "plugin_content.inc.cpp"
return return_value;
}
Note that I use a hack here, the code will be included from another file, "plugin_content.inc.cpp". The code from user will be put inside.
a script to build the plugin, "build_plugin.sh" :
#! /bin/sh
g++ -c -Wall -fPIC plugin.cpp -o plugin.o
gcc -shared -o libplugin.so plugin.o
Now the calling program, main.cpp :
#include <iostream>
#include <fstream> // to open files
#include <dlfcn.h> // C lib to load dynamic libs
#include "plugin.h"
using namespace std;
// load the plugin and call the process() function fom it
static int process_via_plugin()
{
int return_value = -1;
void *lib_handle(NULL);
char *error(NULL);
char *plugin_lib = "./libplugin.so";
lib_handle = dlopen(plugin_lib, RTLD_LAZY);
if (!lib_handle)
{
cerr << "Error loading lib " << plugin_lib << " : " << dlerror() << endl;
exit(1);
}
char *plugin_fn = "process";
plugin_process_fn_ptr fn = (plugin_process_fn_ptr)dlsym(lib_handle, plugin_fn);
error = dlerror();
if (error)
{
cerr << "Error finding lib " << plugin_fn << " : " << error << endl;
exit(1);
}
// call the function loaded from lib
return_value = (*fn)();
dlclose(lib_handle);
lib_handle = NULL; // useless but for good habits ^^
return return_value;
}
// build or rebuild the plugin,
// we must call it when we change the plugin code code
static int build_plugin(string code)
{
{
char *plugin_code_file = "plugin_content.inc.cpp";
ofstream plugin_code(plugin_code_file, ios::out);
plugin_code << code << endl;
}
system("build_plugin.sh");
return 0;
}
// our program
int main(int argc, char *argv[])
{
cout << "Hello World !" << endl;
string code = ""
"cout << \"Hello from plugin !\" << endl;"
"";
// build a first version of the plugin and call it
build_plugin(code);
process_via_plugin();
// now we modify the code (use a GUI here)
code = ""
"cout << \"Hello from plugin, updated !\" << endl;"
"";
// rebuild the plugin and call it again
build_plugin(code);
process_via_plugin();
// do it again as much as you want.
return 0;
}
Now, build your program :
g++ -Wall -rdynamic -ldl main.cpp
and execute it :
a.out
and you get :
Hello World !
Hello from plugin !
Hello from plugin, updated !
The code I give you is very basic. For example, we should check if the compilation of the plugin is successful and report errors to the user. Now it's up to you to add more stuff.