MainClass *mb[1];
Class1 *m1;
cout << "Constructor type (1 - no parameters || 2 - with parameters): ";
int choose;
cin >> choose;
if (choose == 1) {
mb[1] = new Class1;
}
else if (choose == 2) {
mb[1] = new Class1("Red", 1);
}
m1 = dynamic_cast<Class*>(mb[1]);
m1->printEverything();
getchar();
and after that Windows 10 throws me "Program1.exe stopped working".
Trying to add delete mb[1] , but no luck.
Destructor:
~Class() {
cout << endl;
getchar();
}
How can I delete derived class object?
You need to store the object in mb[0] (not mb[1]) because array indexing is 0-based in C and C++ and you only reserved space for one element in mb. Reading from or writing to mb[1] yields undefined behaviour in your program, typically resulting in a crash.
Deallocating your object must be done with delete mb[0]. Not with delete[] which is for deallocating memory allocated with new [].
Deallocation should be done by:
delete mb[0]
You should use mb[0] to access first element of array
Related
This is a snippet of code that I took from a bigger one. I need to figure out whether or not what I'm printing is garbage and how to change it for it to print the value I need.
I need it to print the value of int id instead of whatever it's printing. The output was 10813776 in this run and it, of course, changes whenever I change some code or relaunch DevC++.
The code is:
#include <iostream>
#include <memory> //Memory allocation (malloc)
using namespace std;
int main(){
int id = 0;
int nMemory = 0;
int * pMemory;
pMemory = (int *) malloc(20 * sizeof(int));
while(id < 20){
if (pMemory != NULL){
cout << "Numbers in memory: " << endl;
pMemory = new int[id];
nMemory = *pMemory;
cout << nMemory << endl;
}
id++;
}
delete pMemory;
return 0;
}
pMemory = new int[id];
nMemory = *pMemory;
The first line replaces the array you've malloc-ed with a new uninitialized one, and then tries to read from the first slot of that new array. You shouldn't be assigning directly to pMemory; maybe to pMemory[someIndex], but not to pMemory itself.
Are you trying to read from the pMemory array and assign it to nMemory? If so, change the lines above to this:
nMemory = pMemory[id];
Your entire loop should look more like this:
if (pMemory != NULL) {
cout << "Numbers in memory: " << endl;
while(id < 20) {
nMemory = pMemory[id];
cout << nMemory << endl;
id++;
}
}
Or, with a more idiomatic for loop:
if (pMemory != NULL) {
cout << "Numbers in memory: " << endl;
for (int i = 0; i < 20; i++) {
cout << pMemory[i] << endl;
}
}
(You're also going to have to initialize the array somewhere above this loop. I presume you do that in your real code, but if not: the code you posted allocates an array with malloc() but does not set the items to useful values. Make sure to set them to something meaningful before you then try to read and print them.)
This code is leaking the memory blocks you allocate with malloc() and new[].
You malloc() a block of memory and assign its address to pMemory, then you change pMemory to point at different memory addresses that are allocated with new[]. So you lose the ability to free() the malloc()'ed memory (you are not even trying to call free()).
And, this code is not freeing the memory allocated with new[] correctly. Memory allocated with new[] must be freed with delete[], not with delete. Worse, you are calling new[] 20 times in a loop, but calling delete only once after the loop. So, you are leaking 19 blocks of new[]ed memory, and have undefined behavior freeing 1 block.
Now, to answer your actual question, the code is printing out garbage because the memory you are allocating with new[] is uninitialized, so the data you are trying to print from that memory contains indeterminate values.
I've started learning C++ and I found some problem with pointers. I'm not sure what did I wrong
char *tablica = NULL;
char *ps;
char c;
int i;
cin >> c;
for (i = 0; c != '#'; cin >> c){
if (!(isdigit(c))){
ps = new char[i + 1];
tablica = ps;
tablica[i] = c;
cout << tablica[i] << " na i " << i << endl;
i++;
delete ps;
}
}
for (int n = 0; n < i; n++){
if (islower(tablica[n]))
cout << char(toupper(tablica[n])) << endl;
else if (isupper(tablica[n]))
cout << char(tolower(tablica[n])) << endl;
else
cout << tablica[n] << endl;
}
delete [] tablica;
It should ask the user to write a single char, and then check if it's not a number (first array) - works fine.
Then the second one should change lower case to upper case, but in here the values are incorrect. I wrote this code without pointers and it worked fine.
Can anyone help?
When you do ps = new char[i + 1] you make ps point to some memory you allocate.
When you do tablica = ps you make tablica point to the same memory. You don't copy the actual memory pointed to by ps, only the pointer ps is copied.
That means when you next iteration allocate memory again what you read and stored into the memory pointed to by tablica (and ps) is gone.
In the second loop the memory pointed to by tablica doesn't exist anymore, since last in your previous loop did delete ps (which is itself an error, as it should be delete [] ps). You attempt to dereference memory that no longer is owned by your program.
Unless your exercise is to learn pointers, then use std::vector instead.
You are deleting the memory object to which the tablica pointer is referring.
Instead of doing
tablica = ps;
Use
tablica = new char[i+1];
So that it could create another memory segment for the array to be used later.
This is a simple program I wrote:
using namespace std;
int main() {
string *word = new string[1]; //create a string object
*word = "blablabla"; //assign a string to that object
cout << "String: " << *word << endl;
delete word; //delete object? Causes unexected crash
int *ar = new int [10]; //create array of 10 blocks
ar[3] = 4; //assign a value to bl-3
cout << ar[3] << endl;
delete ar; //delete object, works
return 0;
}
Now from what I understand so far, one uses delete with new (as in delete one object that I created) and delete[] with new[] (delete and create an array of objects). The problem is that the former delete causes my program to crash while the latter works fine. Doing delete[] word works, however.
So how am I creating an array of objects? Am I mistaken in thinking that string *word = new string[1] creates just one object?
So how am I creating an array of objects? Am I mistaken in thinking that string *word = new string[1] creates just one object?
Sort of.
You are creating an array of 1 object.
You are creating one object. That's true. You are still creating an array.
Hence, you need to use the delete [] form.
delete [] word;
and
delete [] ar;
this is a part of an assignment for my programming class. the teacher wanted us to create a couple of functions, one of which would add elements to an existing dynamic array of structures, and this is what I have troubles with.
here's my understanding of how the function should work, based on different posts I found online:
create a new array, bigger than the one already existing
copy the content of the old array to the new array
add the new element to the new array
destroy the old array
however, something is wrong, and the program crashes - I think the problem lies in the way I'm trying to do points 3 and 4. Can someone take a look? I'd really appreciate any kind of help.
edit: forgot to mention, the teacher wants the functions set to void, they are supposed to not return anything.
Here is the code:
const int size = 2;
struct Player {
string name;
string kind;
};
void addplayer(Player * plarr, int size) {
cout << "Adding a new element to the array" << endl << endl;
//creating a new, bigger array:
Player * temp = NULL;
temp = new Player[size+1];
//copying the content of the old array
for (int i=0;i<size;i++) {
temp[i].name = plarr[i].name;
temp[i].kind = plarr[i].kind;
}
//adding the new element:
string name, kind;
cout << "Choose the name for the new player: " << endl;
cin >> name;
cout << "Choose the class for the new player: " << endl;
cin >> kind;
temp[size+1].name = name;
temp[size+1].kind = kind;
//deleting the old array, replacing it with the new one
delete[] plarr;
plarr = temp;
}
void addplayer(Player * plarr, int size) {
The plarr parameter is passed to this function by value.
This function appears to allocate a new array and copy over the contents correctly, except for one error:
temp[size+1].name = name;
temp[size+1].kind = kind;
The index should be size, here. But the biggest error is that the function concludes with:
delete[] plarr;
plarr = temp;
}
Unfortunately, since plarr was passed by value, all this does is set the plarr parameter to this function to the new pointer, and returns.
Which accomplishes absolutely nothing, since the caller to this function still has its original pointer. Which is now destroyed.
You should change this function to return the new pointer, which the caller will need to save, instead of the original pointer.
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int [i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
Now,
why is their a bracket enclosed in variable i?
p= new (nothrow) int [i];
why are their 2 for statements and what does a for statement do exactly?
Why is it deleting []p instead of the variable p?
why is their a bracket enclosed in variable i? &
Why is it deleting []p instead of the variable p?
p= new (nothrow) int [i];
Dynamically Allocates an int array of i elements .
delete []p;
Deletes the dynamically allocated array.
Basic Rules of dynamic allocation in C++ are:
If you use new to dynamically allocate memory, Use delete to deallocate it.
If you use new [] to dynamically allocate memory, Use delete [] to deallocate it.
Also, note that you are using nothrow version of the new operator, it basically returns a null if some error condition and does not throw an exception, this allows the C++ code to be compatible with the legacy c code which uses null check after memory allocations(malloc returns null on failure).
what does a for statement do exactly?
A for statement is a conditional loop construct, It keeps on executing the loop untill the condition remains true. The basic syntax of for loop is:
for(;condition;)
{
//doSomething
}
why are their 2 for statements?
The first for loop in your code gets the input from the user. It takes the input for i times.
The second for loop prints out the contents of the array.
Suggest you to pick up a good C++ book and read through the basics to understand more.
delete[] means that you are freeing an array back to the system, the no brackets for the if statement is optional and just means that the first line will be executed if true, I think you really need to learn some basics in C++ and programing in general, get a good book or google tutorials there are a lot of good ones out there
It is just C++ syntax.
new int [i] means that we want to allocate memory to store i integers.
delete [] p deletes memory bind to p. If [] are omitted, compiler assumes that p points to single instance of *p type. If instruction includes [] compiler tries to remove array of elements.