0

Why the output of codes below is an invalid string? If lines #1 to #3 cannot be changed, how can I assign the value of config.strConfig to data2->str?

// classA.h
#pragma once
#include <string>

class Config {
public:
    int a;
    std::string strConfig;
};

// structA.h
#pragma once

#include <string>

struct Data {
    char test[2];
    std::string str;
};

// main.cpp
#include "classA.h"
#include "structA.h"
#include <iostream>

int main() {
    Data data;  // #1
    memset(&data, 0, sizeof(data));  // #2
    Data* data2 = &data;   // #3
    Config config;         
    config.strConfig = "aaaa";
    data2->str = config.strConfig;
    std::cout << (data2->str) << std::endl;
}
DerekLu
  • 79
  • 2
  • 7
  • 2
    Don't use `memset` on a structure which is not POD. https://stackoverflow.com/questions/6877281/memset-structure-with-stdstring-contained – Devolus Feb 19 '21 at 10:12
  • @Devolus thanks for commenting. However, lines #1 to #3 are codes written by other colleages, and I can only extend the program based on what they had given. I'm confused now how to achieve `data2->str = config.strConfig;` and get a valid result. – DerekLu Feb 19 '21 at 10:16
  • If your colleages gave you buggy code, then they should fix it. – Devolus Feb 19 '21 at 10:17
  • 1
    You can not fix it, because if this is their implementation, and you can not change it, then there is nothing you can do about it until they fixed it. – Devolus Feb 19 '21 at 10:21

1 Answers1

1

You do not need (and shouldn't use) memset (line // #2). This clears the memory bytes without taking into account the container type you are using. Better to write a constructor for Data which sets test[0] and test[1] to zero (if that's what you want) and (optionally) initialises str.

Roger Cigol
  • 173
  • 1
  • 9