سؤال

I have an issue when I try to copy char* data from one struct to another. Here is the struct

struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};

And basically what I am trying to do is to copy the data from one object to another (connection_setup is a private connection_details object) this is the code from the constructor of another object:

settings *tmp = new settings();
this->connection_setup.server = strdup(tmp->getSQLSettings().server);
delete tmp;

I keep getting segmentation fault which is understandable since I probably touch stuff that I should not be doing.

Basically both the settings object and the object I am in contains a private member variable of the type connection_details. I.e

class settings {

public:
    settings();
    ~settings();
    connection_details getSQLSettings();
private:
    connection_details sqldetails;
};

Thanks for any advise!

هل كانت مفيدة؟

المحلول

First of all, you are using new and free together. That is a very bad idea because the destructor will not be called in general. You should replace free with delete.

Moreover, you are getting the ownership for that return value of strdup, yet you do not free it anywhere, but hopefully that is done somewhere in the unshown code.

The problem here seems to be that there is a copy done for the return of the get sql method which will copy the pointer so now you have got two pointers pointing to the same.

This is a problem because when the first gets destructed, it will also destruct the pointer hopefully in your destructor, and when the second would run, you will be trying to delete a dangling pointer... That is probably what is causing the crash for you.

There are several approaches to address this issue:

  • Return reference to avoid the copy.
  • Make a proper copy constructor to copy the data, and not the pointer.
  • Use higher level C++ elements, like std::string, or at least smart pointers, etc.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top