Problem: Values of global vector t1 is not accessible in main destructor function i.e. "after_main()" function. Other types of global variable values are accessible.
PFB Code I have tried & output:
- Declared global vector t1.
- In main function added values in t1
- When printed values inside "after_main()" function, it prints garbage values.
- When printed size it shows correct size of the vector inside "after_main()" function.
From 3rd and 4th point I can say that vector is not getting destroyed but values inside vector are getting destroyed. But I am not able to understand why.
Lifetime of the global variable is entire runtime of the program. Hence vector should not get destroyed during "after_main()" function execution.
Supporting link: https://en.wikipedia.org/wiki/Global_variable
Questions:
- Can someone please explain, why this is happening i.e. why vector is behaving strange?
- I want to access values (any dynamically growing structure like vector) modified during main in "after_main()" function, is there any solution for this?
With Dynamic Vector
#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
vector<int> t1;
void after_main(){
cout << t1.size() << endl; //output: 2
cout << t1[0] << endl; //output: garbage value
cout << t1[1] << endl; //output: garbage value
}
int main(){
t1.push_back(10);
t1.push_back(20);
}
predefined vector size
#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
vector<int> t1(2);
void after_main(){
cout << t1.size() << endl; //output:2
cout << t1[0] << endl; //output:0
cout << t1[1] << endl; //output:0
}
int main(){
t1[0] = 10;
t1[1] = 20;
}
Example of global integer variable accessible in "after_main()" function:
#include
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
int x;
void after_main(){
cout << x << endl;//output: 5
}
int main(){
x = 5;
}
Example of global array variable accessible in "after_main()" function:
#include <vector>
#include<iostream>
using namespace std;
void after_main() __attribute__((destructor));
int x[10];
void after_main(){
cout << x[0] << endl; //output: 10
cout << x[1] << endl; // output: 20
}
int main(){
x[0] = 10;
x[1] = 20;
}