0

I need to write a tree, with nodes being strings (that is important, because I need some string class standard functions).

But when I try to implement my code, everything breaks on the earliest stage:

#include <iostream>
#include <string>

using namespace std;

struct test {
    string str;
    struct test * r, * l;
};

int main() {    
    struct test* node = (struct test*)malloc(sizeof(struct test));
    node->str = "abc";
    cout << node->str;
    return 0;
}

My Visual Studio throws Access violation reading location at me. What frustrates me more is that for int instead of string everything works just fine. So, I need just to be able to use string as a struct member, and to be able to code trees with that struct.

  • 1
    who told you / why do you think you can create a `std::string` in this way via `malloc` ? You can't. – 463035818_is_not_an_ai May 02 '23 at 13:19
  • 4
    simply do not use `malloc` in C++. There is no reason to do so (unless you really know what you are doing). If you read about usage of malloc, it was perhaps in a introduction to C. – 463035818_is_not_an_ai May 02 '23 at 13:20
  • 1
    `test node;` -> all problems gone – 463035818_is_not_an_ai May 02 '23 at 13:21
  • And why do you want/need to use `malloc` instead of using `new test();` – t.niese May 02 '23 at 13:22
  • https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – 463035818_is_not_an_ai May 02 '23 at 13:22
  • 3
    Looks like you are not learning c++ from a good source, your code is half "C" half bad C++. Learn cpp from : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date with the latest guidelines. – Pepijn Kramer May 02 '23 at 13:23
  • The other thing, C++ will NOT initialize variables, When using (member) pointers always make sure they are initialized. E.g `struct test { test* r{nullprt}; test* l{nullptr}; };` (r{} will also be fine) – Pepijn Kramer May 02 '23 at 13:26
  • About malloc, it will not result in constructors being called on structs/classes so in C++ always use `new` (or better std::make_unique to avoid memory leaks) – Pepijn Kramer May 02 '23 at 13:27
  • 2
    `malloc` is a C facility. It cannot construct C++ objects. it does not call constructors, it merely allocates memory. In C++ you can use `new` to allocate memory and construct objects, but in modern C++ calling raw `new` is rare. You'd use smart pointers for dynamic allocations – 463035818_is_not_an_ai May 02 '23 at 13:28

0 Answers0