Stack vs Heap C++

https://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

Heap allocation in C++ is done by using new keyword.

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

struct Node {
string tag;
vector<Node *> children;
};
vector<Node *> nodes;

void process(){
for (int i = 0; i< 3; i++){
Node* n = new Node() ;
n->tag = "a";
nodes.push_back(n);
}
}

int main() {
std::cout << "Hello World!\n";
process();

for (int i = 0; i< 3; i++){
cout<<nodes[i]->tag<<endl;
}
}

above works fine but below will not

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

struct Node {
string tag;
vector<Node *> children;
};
vector<Node *> nodes;

void process(){
for (int i = 0; i< 3; i++){
Node n ; // n is allowed on stack and might be deallocated by OS
n.tag = "a";
nodes.push_back(&n);
}
}

int main() {
std::cout << "Hello World!\n";
process();

for (int i = 0; i< 3; i++){
cout<<nodes[i]->tag<<endl; // this will cause segmentation fault
}
}

Comments

Popular posts from this blog

Perform efficient Latent Semantic Index using Python

SVM

Open Source to E-discovery