How can I declare a stack reference in C++11? - c++

I am implementing a stack reference. However I got the error of 'Segmentation fault (core dumped)'. I am using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 on Ubuntu 14.04. Many thanks.
The code is listed below.
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int>* S;
S->push(4);
return 0;
}

Stop using new wherever you can.
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(4);
return 0;
}

Having "naked" pointers representing object ownership is generally discouraged, as it is error-prone. Either use automatic variables, or the smart pointers provided by the library.
#include <stack>
#include <memory>
int main()
{
// On the stack, local scope. This is the fastest;
// unlike Java we don't have to "new" everything.
std::stack<int> s1;
s1.push(4);
// Dynamically allocated, gets auto-deleted when the
// last copy of the smartpointer goes out of scope.
// Has some overhead, but not much.
// Requires some extra plumbing if used on arrays.
auto s2 = std::make_shared<std::stack<int>>();
auto s2_copy(s2); // can be copied
s2->push(4);
// Dynamically allocated, gets auto-deleted when the
// smartpointer goes out of scope. No overhead, but
// cannot be copied / shared.
// Works out-of-the-box with arrays as well.
auto s3 = std::make_unique<std::stack<int>>();
s3->push(4);
}

you have to create the object then you can point to it.
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int> s;
stack<int>& S = s;
S.push(4);
return 0;
}

Related

Using a big struct as parameter with std async causes bug

I have a big struct that needs to be processed. So I use std async to do it on another thread. Here is a simple example below:
#include <iostream>
#include <future>
using namespace std;
struct teststruct{
float thisvalue[32][32][64];
};
void foo(teststruct thisdummy) {
this_thread::sleep_for(chrono::milliseconds(234));
cout << "hello";
}
int main() {
teststruct thisteststruct;
foo(thisteststruct); // this does work
auto futurevalue = async(launch::async, foo, thisteststruct); //this doesnt work
return 0;
}
I have a struct that is just a big 3d array of floats. When I run this I get an error saying Bus error: 10. Just calling foo without using async works but using std async it doesn't work. Somehow it is related with the struct size since when I make the struct
struct teststruct{
float thisvalue[32][32][63];
};
it magically works. I have tried splitting up the struct by half so a 32x32x32 array instead of a 32x32x64 array and taking in teststructs as parameters but it doesn't work. As I said above I think this has to do with the size of the struct. How can I fix this?
You are probably blowing the stack.
sizeof(teststruct) is 32*32*64*sizeof(float). Assuming a 4-byte float, that's 256KB that you are attempting to pass by value into foo.
While there are flags you can pass to the compiler to increase stack size, you really want to avoid passing large objects by value. As that requires an in-memory copy to be made. Pass that big struct by shared_pointer. That will enable it to be passed around on the main thread and on the async thread without using any significant amount of stack memory. It's also faster since it avoids the large copy of that object.
#include <iostream>
#include <future>
#include <memory>
using namespace std;
struct teststruct{
float thisvalue[32][32][64];
};
void foo(shared_ptr<teststruct> thisdummy) {
this_thread::sleep_for(chrono::milliseconds(234));
cout << "hello";
}
int main() {
auto thisteststruct = make_shared<teststruct>();
foo(thisteststruct);
auto futurevalue = async(launch::async, foo, thisteststruct);
return 0;
}
Making it a pointer or reference should do the trick.
(untested)
void foo(teststruct *thisdummy) {
this_thread::sleep_for(chrono::milliseconds(234));
cout << "hello";
}
int main() {
teststruct thisteststruct;
foo(&thisteststruct); // this does work
auto futurevalue = async(launch::async, foo, &thisteststruct); //this doesnt work
futurevalue.get();
return 0;
}
What the below discussion is about is:
If the std::future obtained from std::async is not moved from or bound
to a reference, the destructor of the std::future will block at the
end of the full expression until the asynchronous operation completes,
essentially making code such as the following synchronous:
See this

How to return a string in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
#include <iostream>
#include<string.h>
using namespace std;
char *rt()
{
char a[20];
strcpy(a,"I am a beginner");
cout<<a;
return a;
}
int main()
{
char *a;
a=rt();
cout<<endl;
cout<<a;
return 0;
}
Here I have made a short program for understanding the same....I was expecting the output to be as
I am a beginner
I am a beginner
UPDATE:
But it turned out to be
I am a beginner
ëóG
I have read many articles and post but I am not able to understand their complex language....so I will appreciate a no-nonsense answer ( for a stupid...like me!!)
UPDATE:
Actually, there is one question in my assignment which goes like this
class COMPUTER
{
char chiptype[10];
int speed;
public:
void showdetails()
{
cout<<chiptype;
cout<<"\t"<<speed;
}
void getdetails()
{
cin.getline(chiptype,10);
cin>>speed;
}
};
Here the data has to be read and stored into a binary file....and the records having chiptype as "CD" are to be displayed.
Now my question is that...as the variable chiptype is private so I can't use it for comparison in main()....so I thought of making a function which returned the value stored in chiptype.
And I am not allowed to use std::string as well as node implementation...
char a[20]; is allocated on stack. When the function rt() returns, the stack unwinds and a goes out of scope. Hence you do not get your desired result.
While you are on C++, may I suggest using std::string
Read the comment below:
The other trick is to wrap the array in a struct, and return the
struct. Since a struct is copyable, the array internally becomes
copyable and will not lose scope. See this answer. Then you're not
dealing with pointers at all. See this live example – PaulMcKenzie
Use std::string instead of char[]
#include <iostream>
#include<string>
std::string rt()
{
std::string a("I am a beginner");
std::cout<<a;
return a;
}
int main()
{
std::string a;
a=rt();
std::cout<<std::endl;
std::cout<<a;
return 0;
}
In your original code char a[20] is allocated on the stack and return a; will return a pointer to a stack variable that is no longer valid when you receive it in you main() -- handling strings in c++ should generally be done using std::string as it handles all the nasty memory management that wil kill your program if you aren't careful.
If you have to use pointers and not use std::string, you would need to go the c style way with the risk of having memory leaks if you miss a step or two. The code would look something like this using c style (keeping the cout c++)
#include <iostream>
#include <strings.h>
std::string rt()
{
char *a = malloc(20); // allocate the memory on heap
strcpy(a,"I am a beginner");
std::cout<<a;
return a;
}
int main()
{
char *a;
a=rt();
std::cout<<std::endl;
std::cout<<a;
free(a); // release the memory
return 0;
}
Caution: I don't recommend that you do the above style -- in a real world application you will likely get into trouble by either forgetting to free the memory, or accidentally accessing the memory after it has been free'd
The problem is that the memory of a will be destroyed as soon as program returns from the function. I do not think you should work with dynamic memory at your level of knowledge, so I suggest you define the array outside and just modify it inside the function:
#include <iostream>
#include<string.h>
#define MAX_LENGTH 20
using namespace std;
void rt(char *a)
{
strcpy(a,"I am a beginner");
cout<<a;
}
int main()
{
char a[MAX_LENGTH];
rt(a);
cout<<endl;
cout<<a;
return 0;
}
Furthermore, you should take care that rt is not writing more than MAX_LENGTH characters.
As mentioned by other use std::string instead of char [].
std::string rt()
{
std:: string a = "I am a beginner"; // This statement is equivalent to std::string a("I am a beginner");
std::cout << a "\n";
return a;
}
Main reason of not getting the desired result is " char a[] is allocated on stack, but when function return stack become empty.
P.S : You need to include <string> in your program, to use std::string

Passing pointer to dynamically allocated array by copy to function has unexpected result

I was just messing around with passing pointers to functions to wrap my head around how it works and I came across some behavior that was unexpected. I have the following code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>
#include <iomanip>
using namespace std;
struct t
{
string x;
string y;
};
void foo(t*);
int main()
{
t* ts = new t[2];
ts[0].x = "t1.x";
ts[0].y = "t1.y";
ts[1].x = "t2.x";
ts[1].y = "t2.y";
foo(ts);
cout << ts[0].x << endl;
}
void foo(t* s)
{
delete[] s;
s = new t[2];
s[0].x = "FOO.X";
s[1].y = "FOO.Y";
}
The output here, interestingly enough, is "FOO.X". I expected that since inside of foo, s is a copy of the pointer ts that when I delete[] s I effectively delete[] ts as they both point to the same address. Then s = new t[2]; should have no effect on ts. After foo returns, I should no longer have access to s or the array it points to and ts should point to who knows where. Am I missing somehthing?
Note: This is just a test project that I made where I constantly write and erase blocks of code to test different concepts. All the includes and using namespace std is for ease of use, and it is NOT code that I am writing for any sort of practical use, purely educational. Also, I am using MS VS 2013.
Try changing your foo() like this and see the result:
void foo(t* s)
{
delete[] s;
// Additional memory allocation
t* u = new t[2];
s = new t[2];
s[0].x = "FOO.X";
s[1].y = "FOO.Y";
}
By adding another memory allocation, I moved s to another location in the memory, which is not anymore overlapping with ts. Otherwise, s was simply allocated at the same location where ts previously resided.
As pointed out in the comments, you are observing an undefined behavior, which you should by no means rely on. The example above illustrates that pretty well.

Destructor gets called before the end of scope

for some reason, after creating an object in main func., the destructor gets called right away, isn't it supposed to get called only when main finishes? thanks
code:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class check{ //create class check
public:
string m_bank_name;
int m_check_number;
int m_branch_number;
char* m_check_sum;
check ( string bank_name, int check_number, int branch_number, char* check_sum){
int a_size = (strlen(check_sum)+1);
m_check_sum = new char[a_size]();
for (int i=0;i<a_size;i++)
{
m_check_sum[i]=check_sum[i];
}
m_bank_name= bank_name;
m_check_number = check_number;
m_branch_number = branch_number;
}
~check (){
delete [] m_check_sum;
cout<<"deleted!"<<endl;
}
};
void main(){
check ob1= check("poalim",809877,12,"4578");
cout<<ob1.m_check_sum<<endl;
getchar();
}
This expression
check("poalim",809877,12,"4578")
creates a temporary object that gets destroyed right after the full expression (;)
Before being destroyed, it is copied to ob1, which is destroyed at the end of the main function.
Perhaps you meant to write
int main(){ //note the correct return type of main
check ob1("poalim",809877,12,"4578"); //direct constructor call
cout<<ob1.m_check_sum<<endl;
getchar();
}
I really suggest that you should read a good book on C++ fundamentals.

Using explicit/raw pointers in c++

I read that using raw pointers in C++ is bad. Instead we should use auto_ptr. In the below code I am populating a vector in foo() that is created in the main(). Am I doing it right or is there a better way to do without using explicit pointers.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string> *v){
(*v).push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(&v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
C++ uses references for what you are trying to do:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
References and pointers are similar, with one very important distinction: there is no such thing as a null reference (Constructing one is Undefined Behavior in C++ you can construct one, but doing so is considered a hack).
In C++ you can avoid the pointer and use a pass-by-reference:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
You can begin to think about using auto_ptr when you deal with objects created on heap (e.g. a class instance created by "new"). Your vector holds its elements by value, std::string elements it is. So you don't need to consider auto_ptr here at all. If your vector would hold instances created on heap then you could use something like this:
std::vector< auto_ptr< MyType > > vec;
auto_ptr< MyType > a( new MyType() );
vec.push_back( a );
and then when your vector elements get erased by e.g. your vec leaving its scope then instance 'a' will get deleted automatically.
With other words, auto_ptr is a kind of garbage collector which does a kind of automatic object deletion for you. See here for more information about auto_ptr http://www.cplusplus.com/reference/std/memory/auto_ptr