Deallocating an array causes an exit 11 code [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am building a project that is composed of Vehicle, Showroom, and Dealership. I've built the classes, and I am testing out my method GetAveragePrice()
float Dealership::GetAveragePrice()
This method was working perfectly:
Dealership dealership("COP3503 Vehicle Emporium", 3);
dealership.AddShowroom(&showroom);
dealership.AddShowroom(&secondary);
dealership.AddShowroom(&third);
cout << "Using just the GetAveragePrice() function\n\n";
cout << "Average price of the cars in the dealership: $" << std::fixed << std::setprecision(2);
cout << dealership.GetAveragePrice();
The output would be
Using just the GetAveragePrice() function
Average price of the cars in the dealership: $27793.60
This is the expected output I wanted, but I was told I have memory leaks and must include a destructor to deallocate my *Showroom showroomList pointer (which I initialized as the following in the Dealership constructor):
this->showroomList = new Showroom[maxNumOfShowrooms];
So I write my destructor as the following:
Dealership::~Dealership()
{
delete [] showroomList;
}
Now, there aren't any memory leaks, but I don't get the expected output and an exit code 11:
Using just the GetAveragePrice() function
Process finished with exit code 11
Does anyone know why this destructor is messing up my output?

This version would delete only once by the last instance standing, in its destructor.
std::unique_ptr<ShowRoom> Dealership::showroomList;
Dealership::Dealership(size_t maxNumOfShowrooms)
:showroomList(std::unique_ptr<ShowRoom>(new Showroom[maxNumOfShowrooms]))
{
}
Dealership::~Dealership()
{
// auto deleted here, with reverse order of initialization
}
but you have a new and delete pair so you should check for deletion only once. This would need some global counter outside of class (or its static variable) and this may not be as readable as smart pointer.
If you are using multiple threads with this, then you could be better with shared_ptr and a custom deleter ([](T * ptr){delete [] ptr;}) as its second constructor parameter.
At least this way you can know if error is about new and delete.

Related

can't return a vector of objects in a fuction due to destructors [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm having some issue with returning vectors of objects of a class in functions because everytime my destructor erases the data twice and all the code just dies when the functions ends
here a simple code I wrote just to show my problem:
#include <iostream>
#include <vector>
using namespace std;
class identity{
public:
string name;
identity(string Name);
~identity();
};
vector<identity> function();
int main(){
function();
cout << "Hello world!";
}
identity::identity(string Name)
: name{Name}{
cout << "Object created!" << endl;
}
identity::~identity(){
cout << "Object " << name << " destroyed!" << endl;
}
vector<identity> function(){
identity me("Isaias");
}
in this case the cout "Hello world" doesn't work and the program always ends with "Object" without displaying the name like this:
Object created!
Object Isaias destroyed!
Object
and then the program just stops. I kind of fixed the problem by seting the type of the function to "void" or anything else instead of "vector" but I'd like to know why this problem occurs. Also I'm new to programming in general and in this community so I'm sorry if I'm not doing this in the right way.
I'd like to thank you all for your attention before anything and sorry again if i am messing everything up here.
vector<identity> function(){
identity me("Isaias");
}
The behaviour of the program is undefined because you don't return anything from the function even though you've declared that the function returns a vector<identity>.
To fix the bug, return a value. Example:
using namespace std::string_literals;
return {"Isaias"s};
Another bug is that you've chosen to use using namespace std, but you've declared identity which is an identifier that is already in the std namespace. This makes the program ambiguous and ill-formed.
To fix this, choose another name for the class, such that the name doesn't conflict with any of the current or future names in the std namespace. This is very difficult because there are many names in std and you cannot predict the future. There is a simpler solution though! Simply don't use using namespace std.
Third bug is that you've used std::string without including the header that defines it. The consequence is that the program may not necessarily compile in any current or future language implementation.
Solution: Include the header <string>.

Pushing a DirectX object into a std::queue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm working on a small release manager that will be used to delete objects once they are old.
I'm using a std::queue to hold the age & pointer to the object.
This is the method that I'm using to push values into the queue:
ID3D12Resource* texture; // declaration
renderPlat->PushToReleaseManager(texture);
std::queue<std::pair<int,void*>> mResourceBin; // declaration
void RenderPlatform::PushToReleaseManager(ID3D12Resource* res)
{
if (!res)
return;
mResourceBin.push(std::pair<int, void*>(0, res));
}
But this is causing an Exception thrown: read access violation / std::_Deque_alloc<std::_Deque_base_types<std::pair<int,void * __ptr64>,std::allocator<std::pair<int,void * __ptr64> > > >::_Myoff(...) returned 0x6B0 :
void push_back(value_type&& _Val)
{ // insert element at end
this->_Orphan_all();
_PUSH_BACK_BEGIN; // <--- The exception is thrown here!!!
this->_Getal().construct(
_Unfancy(this->_Map()[_Block] + _Newoff % _DEQUESIZ),
_STD forward<value_type>(_Val));
_PUSH_BACK_END;
}
The object that I'm trying to delete, is an ID3D12Resource it inherits from IUnknown
Edit:
I'm using: Visual Studio 2015 (v140).
Edit 2:
The ID3D12Resource* object passed to the PushToReleaseManager() is created using ID3D12Device::CreateCommittedResource
I found the problem.
I was getting the RenderPlatform which has the PushToReleaseManager() method like this:
auto rPlat = (dx11on12::RenderPlatform*)(renderPlatform);
This cast was failing because renderPlatform was invalid and it was returning a null pointer. The thing is that I was allowing me to call the method no problem, I guess because it had some junk memory around.
Thanks for the answers!
Try to use smart pointers. They are much better then explicitly try to release memory.

Classic List of object in C++ using pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'd like to make one directional list of objects in C++. I've got 3 classes: BasicMiachine,Desktop,Laptop. Two last classses extends BasicMachine. What I want to do is make a list of object (Desktop,Laptop) using only one list. In Basic Class which is abstract class (because I have declare one method as virtual) I have a field which is a pointer to next object is a BasicClass type. Below is my code:
int main () {
BasicClass* headList= NULL;
BasicClass* iterator = NULL;
while(....)
{
switch(.....){
case 1:
addNewComputer(headList,iterator,numberOfObjects);
break;
}
}
void static addNewComputer(BasicClass* headList, BasicClass* iterator,short numberOfObjects)
{
short choice;
cout<<"What is your machine?"<<endl<<"1) Desktop or2) Laptop"<<endl;
cout<<"Your choice: "; cin>>choice;
if(choice== 1)
{
//Add some data to variables// ....//
if(numberOfObjects == 0)
{
headList = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
iterator= headList ;
iterator->nextObject = NULL;
}
else
{
BasicClass* tmpIterator= NULL;
tmpIterator= headList ;
tmpIterator->nextObject = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
tmpIterator= pomocniczyWskaznik -> nextObject;
tmpIterator->nextObject = NULL;
}
}
else if(choice == 2)
{
//It is the same as above but I add here a La
}
};
After I add one and second computer I got an error like: "Access violation writing location 0x00000050." Is it a problem with pointers? I use BasicClass type pointers to hold both objects (Desktop, Laptop).
You make the classic mistake of passing pointers by value instead of by reference.
Change addNewComputer to e.g.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
and things should work better.
I suggest you to take a look to standard containers. Anyway, the problem is that your are passing pointers by value, so when you call "new" the pointer inside addNewComputer() points to a new memory direction and when the function returns, headList and iterator are null (notice the memory leak issue). To solve your problem, you need to pass headList and iterator by reference i.e.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
Hope this help.

trying to use my custom class constructor without new [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
coming from java i would like to not have to deal with de-allocation when creating new custom or other library's objects.
today i was trying to create an instance of my entity object like:
entity cube = new entity("entityName")
because this is how entity's constructor is formatted
but i get the following error:
cannot convert from |entity *| to |entity|
i noticed there are no errors if i just remove the new keyword, and i was wondering two things.
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
new entity("entityName")
means "create an instance of entity in the free store and return a pointer to that instance".
Since a pointer to an entity is not the same as an entity, you cannot initialise an entity with that value unless you have yet another constructor.
The way to do what you want is
entity cube("entityname");
And you need a good book on C++.
First, I suggest you to read a C++ tutorial. It has much more complexity than Java.
This is a very partial Java to C++ "how to convert" guide that I can give you:
Java code:
void sayHello(String name) {
system.out.println("Hello, " + name);
}
public static void main(String args[]) {
String name = "James"; // <-- This string is of course created in the dynamic memory
sayHello(name); // <-- "name" will be passed by reference to the "sayHello()" method
}
Equivalent in C++ - option 1:
void sayHello(const std::string &name) {
std::cout << "Hello, " << name << std::endl;
}
int main() {
std::string name("James"); // <-- Variable is created on the stack
sayHello(name); // <-- Although "name" is not a pointer, it will be passed by reference to "sayHello", as "name" is defiend there with "&", which means that it is a reference
}
A reference is a very "weird" type - it behaves like a local variable, although it actually points to an instance that does not have to be on the stack of the current function or on the stack at all.
C++ - option 2:
void sayHello(const std::string *name) {
std::cout << "Hello, " << *name << std::endl; // <-- dereferenceing "name" using a preceding star, as "cout" needs the variable itself and not its address
}
int main() {
std::string *name = new std::string("James"); // <-- Instance is created in the dynamic memory
sayHello(name); // <-- Sending the pointer "name" to the "sayHello" function
// You will need to free "name" somewhere in the code unless you don't care about memory leaks
}
There are more options, like passing the instance by value (not recommended in such case), or like creating it in the dynamic memory and deref
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
No. C++ is different about this, you don't use an allocation (new) to initialize cube:
entity cube("entityName");
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
No. See above. ("because there are no errors." I doubt this, there should at least be compiler warnings if you assign entity from a pointer.)

using cin in other headers C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to get three variable from the user by using in my own header ...
here's the piece of the code i have written ...
<class T>
Sparse<T>::Sparse(){
std::cout << "Please Enter The Following Information" << std::endl << "Row:" ;
std::cin >> this->rows;
std::cout << "Column:" << std::endl;
std::cin >> this->column;
std::cout << "Please Enter The Number of TermS:" << std::endl;
std::cin >> this->term;
}
i used forward decelaration for in my own header :
class cin;
the problem i've encountered is as you can see there is no loop for the function of the class But ...
when i run the code, the compiler runs this block multi_Times ...
Like the cin just can't initialize the variable ...
Like this
"Please Enter The Following Information"
"Rows:"
"Columns:"
"Please Enter The Number of TermS:"
"Please Enter The Following Information"
"Rows:"
"Columns:"
"Please Enter The Number of TermS:"
Please Help .....
Extra Detail ....
As Mr.Coffin Said I Want to use "Forward declaration" Please Help ME ...
How do i must use ...
cause including a header in another header is such a bad style to use ...
And yes i have two constructor one gets the argument for the
the other works this way ....
and it is because i dont want to have cin and cout and lots of equalation (=) in my main ...
Thanks Mr.Coffin ....
The constructor of a class is there for the initial creation of the object. In this example, this is the default constructor. In general you probably don't want to write user-facing questions in the constructor of a class, let alone the default constructor.
Writing it your way means that any time you create an uninitialized Sparse, the user will be asked these questions.
Sparse<int> a, b;
This calls the constructor twice, asking the questions twice, forcing the user to answer the questions without knowing which 'Sparse' they are being questioned over.
Sparse<int> a, b;
if (day == "Monday") {
a.something();
} else {
b = a;
}
Here the user is prompted with questions that only make sense one day of the week.
But you also run into problems like:
std::vector<Sparse<int>> manySparses;
manySparses.resize(1000);
The user is now going to be asked the questions ... 1000 times.
Choose one of two approaches: Ask the questions BEFORE you construct the object; or choose sensible default values - e.g. values that indicate "I don't have values yet" and then populate the values after construction,
You could have a static member for asking the question or you could have a member that asks them after the object is constructed:
Sparse<int> a, b;
a.GetConstraints();
if (day == "Monday")
b.GetConstraints();
else
b = a;
But don't write a default constructor that asks the user questions like this.
---- Edit, regarding 'cin' ----
'cin' is not a class. It's an object. For portability, and just down right good practice, you shouldn't go injecting your own attempt to declare standard library types/structs/functions like this, especially not in headers.
Instead, accept it as a dependency and
#include <iostream>
in your header file before you try to use it.
---- Edit: final notes ----
When you think of "Construction" in the programming sense try to think on the scale of "deciding I'm going to build a skyscraper" rather than "undertaking the work of building the empire state building, selling space on the 101st floor and hiring a management team".
It's not that you can't/shouldn't write complex constructors, but your goal should simply be to get the object into a reliable state for the program.
class string {
public:
string() {
std::cout << "Enter the string you want: ";
std::cin >> m_string;
m_length = strlen(m_string);
}
...
};
vs
class string {
public:
string() : m_string(NULL), m_length(0) {}
...
};
Secondly, having a constructor which talks to standard input/output fundamentally cripples its usefulness. There's no problem with using that logic to obtain the values from the user, but if you put it into the class's constructor then the class can only be used in an application that has standard input/output (neither gui nor headless apps need apply).
Thirdly, how will you handle errors? What if cin gets closed after the first question? Your code doesn't check for it, and if it did, it would have to pass the burden to whomever is creating the object. Nobody expects to have to write
try {
Object myObject; // may fail if user types 'wibble' instead of '13'.
} catch (wibble_input_as_columns_exception& e) {
std::cerr << "Damnit, Dave, 'wibble' is not a valid number of columns." << std::endl;
}