shared_ptr

Hello!

I am currently practicing shared_ptr's, but for some reason my code always gives me a Run Time Error at one particular line ("cout << crt << "Class -> " << _Class << crt;"). So far whatever I've done, I've been unable to figure out what the problem would be.

Does anyone know what the reason could be?

Due to the number of lines, the code is pasted on pastebin.com/nhFZm3xF instead of in the topic.
Last edited on
> I am currently practicing shared_ptr's
and yet I see raw pointers everywhere.


lines numbers have a +5 offset because of adjustments to make your code compile (including `cstring' and defining `strcpy_s()')
$ gdb a.out
(gdb) run
[output removed]
Program received signal SIGSEGV, Segmentation fault.
0x00000000004035e9 in Success::Output (this=0x0) at foo.cpp:94
94	        cout << crt << "Class -> " << _Class << crt;
(gdb) backtrace
#0  0x00000000004035e9 in Success::Output (this=0x0) at foo.cpp:94
#1  0x0000000000403f76 in Candidate::Output (this=0x60f000000048) at foo.cpp:136
#2  0x0000000000402247 in main () at foo.cpp:228
(gdb) frame 1
#1  0x0000000000403f76 in Candidate::Output (this=0x60f000000048) at foo.cpp:136
136	            _Success[i]->Output();
(gdb) print i
$1 = 2
(gdb) print _Success
$2 = {std::shared_ptr (count 1, weak 0) 0x604000000260, std::shared_ptr (count 1, weak 0) 0x604000000120, 
  std::shared_ptr (empty) 0x0, std::shared_ptr (empty) 0x0}
(gdb) quit

`student[0]' had no TRECI DodajSubject so its pointer remained null. You should check that before trying to dereference it.
You need to include string.h as you use C string calls.

Constructs like:
1
2
3
        int vel = strlen(name) + 1;
        _name = new char[vel];
        strcpy_s(_name, vel, name);

can be replaced with:
 
        _name = strdup(name);


Constant strings are of type const char* because you can't change them. So, for example, this:
 
char *crt = "\n-------------------------------------------\n";

should be this:
 
const char *crt = "\n-------------------------------------------\n";

There are lots of these warnings, so take a look please.

This declares an array of 4 shard_ptrs, each initialized to null.
 
shared_ptr<Success> _Success[4];


When Candidate::Output() runs, _Success is still an array of nulls. You crash when you' dereference the first one.
Last edited on
Topic archived. No new replies allowed.