Initializing c-string in a constructor

The data members of the class are

private:
char* name;
Party party;
int intensity;

and my constructor looks like this

Voter::Voter(const char * const name, const Party party, const int intensity)
{
this->party = party;
this->intensity = intensity;
strcpy(this->name, name);
}

When I try to compile it I get a segmentation fault, and I'm pretty sure it has to do with the strcopy part of it but I can't figure out why. Any thoughts?
You haven't allocated space for the this->name, so you're copying the name into who-knows-where.

Can you use C++ strings instead? They will remove a ton of potential errors.

If you must use C strings, then you can allocate and copy the data with this->name = strdup(name); Just be sure to free the space in the destructor. And you better write a copy constructor and assignment operator (and move versions of the same).
this->name has not been allocated any memory to hold the incoming name which also suggests the need for a less confusing variable naming system
Would something like this work?

char * tempName = new char[strlen(name) +1];
this -> name = tempName;
delete tempName;

Or would that deleting temp name deallocate the memory that name is now pointing to? I'm not very familiar with strdup so i figured i'd try a way more familiar. I have to use cstrings for this, and we can't create a copy constructor either. Also what do you mean by write an assignment operator? Overloarding the assignment operator?
> I have to use cstrings for this, and we can't create a copy constructor either.

If a user-defined copy constructor is not allowed, it is clear that dynamic allocation is not to be used.

Something like this, perhaps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct voter
{
    static constexpr std::size_t MAX_NAME_SZ = 128 ;
    char name[MAX_NAME_SZ+1] ; // +1 for an additional null character at the end

    voter( const char* name_str /* ... */ )
    {
        std::strncpy( name, name_str, MAX_NAME_SZ ) ; // copy at most MAX_NAME_SZ characters
        name[MAX_NAME_SZ] = 0 ; // null terminate: std::strlen(name_str) could be >= MAX_NAME_SZ
                                // in which case std::strncpy wouldn't have terminated with a null

        // ...
    }

    // ..
};
Topic archived. No new replies allowed.