CHAVE_
CHAVE_

Reputation: 39

Assign custom string to string attribute in C++

So, I have a struct:

typedef struct _connection {
    int socket;                 // host-to-client socket id.
    struct sockaddr address;    // address of client. 
    int address_length;         // length of address field.

    std::string user;
    std::string group; 

    int connected;
}

and a main code where conn is an instance of this struct:

char buffer[256];
std::string s = std::string(buffer);
conn->user  = s.substr(0, s.find(' '));

However, the last line gives a Segmentation Fault. I know for a fact that connis not null, nor is s.substr(0, s.find(' ')) null. Is there a rule in struct assignments I'm unaware of?

Upvotes: 0

Views: 156

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You can construct a temporary std::string that will be move assigned (instead of copied) into s.user directly like below. The potentially dangerous creation of s from the not necessarily null-terminated buffer is not needed:

#include <algorithm>
#include <iterator>

s.user = std::string(std::begin(buffer),            // create a string from the start
                     std::find(std::begin(buffer),  // find from the start
                               std::end(buffer),    // ... to the end
                               ' '                  // ... and look for space
                              )
                    );

This uses the std::string constructor that uses iterators. The first points to where to start copying and the second iterator points at the end, which is what std::find will return.

If no space is found, the whole buffer will be used.

Also worth noting: The typedef you have is just ignored, so just remove it:

struct _connection {
    // ...
};

Upvotes: 2

Related Questions