Part of a larger program I am making requires a path to be read in from the command line and stored in a class. Because paths can be an arbitrary size and it’s needed in multiple functions, I store it in a char* in the header file. But, for some reason, when I assign a value to it, the program segfaults.
The debugger (gdb) shows the following:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b4828a in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char> >(std::basic_istream<char, std::char_traits<char> >&, char*) ()
from /usr/lib/libstdc++.so.6
Here’s the program I wrote to demonstrate the problem:
test.cpp:
#include "test.h"
#include <iostream>
#include <cstring>
Test::Test() {
filepath = NULL;
}
void Test::set_path(char* string) {
char temp[strlen(string) + 1];
strcpy(filepath, temp);
}
char * Test::get_path() {
return filepath;
}
int main(int argc, char *argv[]) {
std::cout << "Enter a file path: ";
char *temp;
std::cin >> temp;
Test *temp2 = new Test();
temp2->set_path(temp);
std::cout << "Path: " << temp2->get_path() << std::endl;
}
test.h:
#ifndef TEST_H
#define TEST_H
class Test {
private:
char *filepath;
public:
Test();
void set_path(char *);
char * get_path();
};
#endif // TEST_H
I’m not sure why it crashes. Is there something wrong with the method I’m doing this? Also, rather than just switching to strings, I’d like to find out more about this problem.
Thanks in advance!
temp(insidemain) is uninitialized and not pointing to any valid allocated block of memory, therefore the line:is causing input to be written into some unknown part of memory, causing undefined behaviour. You should either:
tempachar[]and only read in an amount of characters that will fit in the buffer.tempto a valid buffer.tempanstd::string, and let thestd::stringclass worry about the memory management.You’re also going to be having a similar problem with
filePathafter you fix the above problem.filePathis being set toNULLin theTestconstructor, and then you’re copyingtempto the block of memory pointed byfilePathinTest::set_path:NULLrefers to an address that you’re not allowed to dereference. You should change all of your C-strings tostd::strings and use thestd::stringmember functions and overloaded operators to deal with strings in C++.