Segmentation fault

江枫思渺然 提交于 2019-12-13 05:46:57

问题


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();
}

回答1:


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.




回答2:


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.




回答3:


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)



来源:https://stackoverflow.com/questions/15296376/segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!