简体   繁体   中英

Segmentation fault

Tried to trace, but did not find a reason why the following code is giving "Access violation" in VC++, and segmentation fault in gcc..

#include <vector>
#include <iostream>
using namespace std;

typedef struct node
{
    std::string data;
    vector <struct node*> child;
}NODE, *PNODE;

int main()
{
    PNODE head;
    head = (PNODE) malloc(sizeof(NODE));

    head->data.assign("hi");

    printf("data %s", head->data.c_str());
    getchar();
}

And why on earth do you think it should work? You use malloc , rather than new , so no constructors are called, and everything you do accesses uninitialized memory.

Use new rather than malloc to create C++ objects on the heap.

The following:

head = (PNODE) malloc(sizeof(NODE));

should read

head = new NODE;

The reason malloc() doesn't work here is that it doesn't call object constructors.

I agree with previous answers.

I should add that it's best practice to avoid using namespace (see here )

And in C++, avoid using C-like struct declaration :

typedef struct node
   {
       std::string data;
       vector  child;
   }NODE, *PNODE;

should be:

struct Node
{
    std::string data;
    std::vector<Node> child;
}

then:

Node head;

or:

Node* head = new Node;

If you are using c++, use std::cout instead of printf

There are c++ cast operator too : dynamic_cast , static_cast , const_cast , reinterpret_cast (see here )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM