Unable to manually free memory from queue of arrays - c++

#ifndef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <Windows.h>
#include <queue>
using namespace std;
void addSomeContent(queue<TCHAR*> &output)
{
TCHAR* buffer;
for(int i=0; i < 10000; i++)
buffer = new TCHAR[1000];
}
int main()
{
queue<TCHAR*> foo;
char sign;
beginning:
addSomeContent(foo);
while (!foo.empty())
{
delete [] foo.front();
foo.pop();
}
wcout<<TEXT("Press y to repeat\n");
cin>>sign;
if(sign == 'y' || sign == 'Y') goto beginning;
return 0;
}
Each iteration of this program uses up 20MB of RAM. Why is it not dispatched by this instruction?
while (!foo.empty())
{
delete [] foo.front();
foo.pop();
}

Perhaps it's because while you pass the reference of foo to addSomeContent, and addSomeContent uses it as the variable named output, addSomeContent is allocating all kinds of memory but never placing those allocations in output, so back in main, foo is empty.
At SO we want to be helpful but we really want people to try to help themselves first. This would be a simple problem for you to have spotted on your own if you have done a little debugging before you posted.

You're trying to delete[] memory manually. This is always bad. Use std::queue<std::vector<TCHAR>> instead. Also, goto? This is bad and you should feel bad.
If you want to add an item to the queue, you need to call a member function on it.
The following code might actually function and might not drive anyone looking at it to insanity.
void addSomeContent(std::queue<std::vector<TCHAR>> &output)
{
for(int i=0; i < 10000; i++)
queue.push_back(std::vector<TCHAR>(1000));
}
int recursive_main() {
std::queue<std::vector<TCHAR>> foo;
addSomeContent(foo);
while(!foo.empty()) foo.pop(); // no need to delete
std::wcout << L"Press y to repeat\n";
char sign;
std::cin >> sign;
if (sign == 'y' || sign == 'Y') return recursive_main();
return 0;
}
int main()
{
return recursive_main();
}

Related

Segmentation Fault Passing Reference as Function Parameter

With this block of code, I'm getting a segmentation fault as I try to pass the stack references to the transferStacks() method. Any help on understanding why this is would be helpful!
I could just get rid of the helper method and it should work, but I'm trying to understand conceptually.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
void transferStacks(stack<int> & s1, stack<int> & s2){
if (s1.empty()){
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int queries = 0;
cin>>queries;
stack <int> newestOnTop;
stack <int> oldestOnTop;
while (queries!=0){
int type = 0;
cin >> type;
int input = 0;
if (type == 1){ //enqueue
cin>>input;
newestOnTop.push(input);
}
else if (type == 2){ //dequeue
transferStacks(newestOnTop, oldestOnTop);
oldestOnTop.pop();
}
else if (type == 3){ //peek
transferStacks(newestOnTop, oldestOnTop);
cout<<oldestOnTop.top()<<endl;
}
queries--;
}
return 0;
}
Segmentation Fault
You appear to believe that this code will copy s2 to s1:
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
But it will not: if before the loop s2 contains 3 elements, only the first 2 will be copied (and generally, only the first half will be copied).
In addition, your transfer function transfers from s2 to s1, but the way you call it implies that you intended the opposite: to transfer from s1 to s2. Current code would leave oldestOnTop empty, which will then result in a crash when you use oldestOnTop.top() or oldestOnTop.pop().

Dynamic Array Using Strings in a Function Issues

I'm trying to run a dynamic array that employs strings, but when I push it through a function I get compile errors 'dynamicArray': undeclared identifier, 'string':undeclared identifier, and illegal use of type 'void'. All of these errors point to the header for some reason.
I call the pointer here:
string* dynamicArray = NULL;
I call the function here:
populateArray(dynamicArray);
What is in the header:
void populateArray(string *&dynamicArray);
The function:
void populateArray(string *&dynamicArray)
{
char decide;
bool moreStrings = true;
int counter = 0;
while (moreStrings == true)
{
counter ++;
dynamicArray = new string[counter];
cout << "\nEnter your string here:";
cin >> dynamicArray[counter - 1];
cout << "\nDo you want to enter another string? Y/N:";
cin >> decide;
decide = toupper(decide);
if (decide == 'N')
{
moreStrings = false;
}
}
}
PS: vector may be better, but I'm afraid that isn't an option. Please only offer fixes that deal with pointers.
With #include <string> and using namespace std; added, it compiles just fine for me.
#include <string>
#include <iostream>
using namespace std;
void populateArray(string *&dynamicArray);
int main(){
string* dynamicArray = NULL;
populateArray(dynamicArray);
return 0;
}
void populateArray(string *&dynamicArray)
{
char decide;
bool moreStrings = true;
int counter = 0;
while (moreStrings == true)
{
counter ++;
dynamicArray = new string[counter];
cout << "\nEnter your string here:";
cin >> dynamicArray[counter - 1];
cout << "\nDo you want to enter another string? Y/N:";
cin >> decide;
decide = toupper(decide);
if (decide == 'N')
{
moreStrings = false;
}
}
}
You need to include <string> in your header file.
BTW, there might be potential memory leak in your code, if moreString is true, dynamicArray will point to another new string array, without deleting current one.
I see a bigger problem than the missing include and the using clause...
You wrote:
dynamicArray = new string[counter];
But this will allocate a new memory area for you every time. It does not copy the previously allocated elements. IF you don't want to use std::vector, you need to use malloc for the first element and than call realloc to copy your previously allocated data to your new one.
Check this form more info: What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

C++: How do you create a return function that returns a vector/array?

This is the motivation behind the code. There is a boy named Bob and its his birthday today. He invites 50 friends over but not all of his friends want to buy him gifts. Bob is presented with 50 presents, though some of them are empty. His good friends tell him to close every 2nd box. For every third box, he is supposed to change every closed to open and every open to closed. He continues to do this for every n-th box where n is less than 50. The open boxes in the end will have the presents.
This is supposed to assist me in figuring out a problem for my math class, but I am not aware of all the complicated aspects of C++ programming. I want my string getValue(vector &arr) to return an array/vector. This code doesn't compile but it shows what I'm trying to do.
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
string getValue(vector<string> &arr);
int main()
{
vector<string> myArr(2);
vector<string> newArr(2);
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
newArr = getValue(myArr);
for(int i=2; i <=50; i++)
{
cout << i << " " << newArr[i] << endl;
}
}
string getValue(vector<string> &arr)
{
for(int i=2; i <=50; i++)
{
if(arr[i]=="close")
{
arr[i]="open";
}
else if(arr[i]=="open")
{
arr[i]="close";
}
}
return arr;
}
You can't make your string getValue(vector<string> &arr) return an array/vector. It can only return a string. If you want a function to return an array/vector, then you have to say so in the function signature.
You're passing the vector into getValue() by reference, which means changes you make to it in that function will affect the original (in other words, you're not operating on a copy of the vector - you're actually operating on the vector).
So you don't need to return anything from getValue() - just make it void and it should do what you want.
string getValue(vector &arr) - the return type is string, not vector. You need to change its return type or set it to none.
PS:
newArr = getValue(myArr);
it's behind the SCOPE and it's wrongly positioned...
damn, third PS, wrong code rules are assigned
For the syntax part :-
The return type of the function is a string. Change it to vector for
your function to work properly.
You can simply declare the vectors globally. This will eliminate the
need to pass it to the function as well as return it.
For the logic part :-
Your question says that Bob toggles every third box but in your program Bob is changing every box to open if it is closed and every box to close if it is open. If what you wrote in the question is correct your code should be like this.
#include <iostream>
#include <vector>
using namespace std;
void getValue();
vector<string> myArr(2);
int main()
{
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
getValue();
for(int i=2; i <=50; i++)
{
cout << i << " " << myArr[i] << endl;
}
}
void getValue()
{
for(int i=3; i <=50; i+=3)
{
if(myArr[i]=="close")
{
myArr[i]="open";
}
else if(myArr[i]=="open")
{
myArr[i]="close";
}
}
}

C++, using stack.h read a string, then display it in reverse

For my current assignment, I have to use the following header file,
#ifndef STACK_H
#define STACK_H
template <class T, int n>
class STACK
{
private:
T a[n];
int counter;
public:
void MakeStack() {
counter = 0;
}
bool FullStack() {
return (counter == n) ? true : false ;
}
bool EmptyStack() {
return (counter == 0) ? true : false ;
}
void PushStack(T x) {
a[counter] = x;
counter++;
}
T PopStack() {
counter--;
return a[counter];
}
};
#endif
To write a program that will take a sentence, store it into the "stack", and then display it in reverse, and I have to allow the user to repeat this process as much as they want. The thing is, I am NOT allowed to use arrays (otherwise I wouldn't need help with this), and am finding myself stumped.
To give an idea of what I am attempting, here is my code as of posting, which obviously does not work fully but is simply meant to give an idea of the assignment.
#include <iostream>
#include <cstring>
#include <ctime>
#include "STACK.h"
using namespace std;
int main(void)
{
auto time_t a;
auto STACK<char, 256> s;
auto string curStr;
auto int i;
// Displays the current time and date
time(&a);
cout << "Today is " << ctime(&a) << endl;
s.MakeStack();
cin >> curStr;
i = 0;
do
{
s.PushStack(curStr[i]);
i++;
} while (s.FullStack() == false);
do
{
cout << s.PopStack();
} while (s.EmptyStack() == false);
return 0;
} // end of "main"
UPDATE
This is my code currently
#include <iostream>
#include <string>
#include <ctime>
#include "STACK.h"
using namespace std;
time_t a;
STACK<char, 256> s;
string curStr;
int i;
int n;
// Displays the current time and date
time(&a);
cout << "Today is " << ctime(&a) << endl;
s.MakeStack();
getline(cin, curStr);
i = 0;
n = curStr.size();
do
{
s.PushStack(curStr[i++]);
i++;
}while(i < n);
do
{
cout << s.PopStack();
}while( !(s.EmptyStack()) );
return 0;
You're on the right track, but you shouldn't be looping until the stack is full -- there are no guarantees curStr consists of at least 256 characters. Instead, loop like as follows...
int n = curStr.size();
do {
s.PushStack(curStr[i++]);
} while (i < n);
Now, you should really not write <bool-expr> == false or <bool-expr> == true... instead, merely write !<bool-expr> and <bool-expr>, respectively. You don't need all of your auto storage specifiers on the local variables, either. Your professor should also look into using the constructor rather than using MakeStack.
edit: It appears you had some trouble translating my code. You only need to i++ once per loop -- this increments our position in the string. As you are doing it now, you are actually incrementing the position twice and thus only pushing every other character.
Use a linked list instead of array in stack.
In the linked list, always store the tail pointer of your list's last node. Each node maintains a reference to your prev node.
A <--- B <---- C (tail)
push:
A <--- B <---- C <---- D (tail)
pop:
A <--- B <---- C (tail)
// D is popped out
when the tail == null, you know it is an empty stack

C++ Int getting random value after function that isn't supposed to change it

Okay - yes, this is homework, but it isn't mine. I have a friend taking an introductory C++ course who asked me for help, and I helped them write this program, but there is one weird bug that I can't figure out. Any helpful suggestions would be greatly appreciated. Thanks!!
The following is the code. The problem is that after the add_loop function, the int loop_size gets a random value. Within the function, it has the value it is supposed to have, but afterwards, it changes.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define STRING_SIZE 50
void get_template (char StemLoop [])
{
char Template [STRING_SIZE];
cout<<"Please enter a template for the stem:";
cin>> Template;
strcpy (StemLoop, Template);
}
void add_loop (char StemLoop[], int loop_size)
{
char random_loop [STRING_SIZE];
int random_array[STRING_SIZE];
for (int i=0; i<loop_size; i++)
{
random_array[i] = rand() % 4;
if (random_array[i]==0)
random_loop[i]='A';
else if (random_array[i]==1)
random_loop [i]='U';
else if (random_array[i]==2)
random_loop [i]='G';
else if (random_array[i]==3)
random_loop [i]='C';
}
strcat (StemLoop, random_loop);
}
void add_complement(char StemLoop[], int loop_size)
{
int x =strlen(StemLoop);
int j=0;
char complement [STRING_SIZE]="";
for (int i=0; i<(x-loop_size); i++)
{
if (StemLoop[i]=='A')
complement[j]='U';
else if (StemLoop[i]=='U')
complement[j]='A';
else if (StemLoop[i]=='G')
complement[j]='C';
else if (StemLoop[i]=='C')
complement[j]='G';
j++;
}
strcat(StemLoop,complement);
}
void main()
{
int loop_size=0;
cout<<"Please enter the size of the loop: ";
cin>>loop_size;
char StemLoop [STRING_SIZE];
//Part1: the template
get_template (StemLoop);
//This is supposed to be the function that adds the loop of random "genes".
//It works, and within it the int loop_size is the correct value...
add_loop (StemLoop, loop_size);
/*...but here it is a random number. It's as if the random value generated
within the function is getting assigned to it. And of course, it's throwing off the
entire program.
*/
//Part#3: the complement
add_complement (StemLoop, loop_size);
cout<<"The complete stem-loop strand is:"<<StemLoop<<endl;
}
You're not 0-terminating random_loop before you use it in strcat, so strcat can write all over your stack. Try this:
random_loop[i] = 0;
strcat (StemLoop, random_loop);
A more serious problem could be that you're not checking you have enough room to strcat.