delete a copied pointer [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 6 years ago.
Improve this question
Is deleting a copied pointer the same as deleting the original pointer?
int * a = new int;
*a = 8;
int *b = a;
delete b;
In the code above, after deleting b, should i still delete a?
In the real code I have problem with, i did
std::vector<ifstream * >Infiles(5);
for (int i = 0; i < 5; ++i){
ifstream * ptr = new ifstream;
(*ptr).open(file_names[i].c_str());
Infiles[i] = ptr;
}
/* doing a bunch of reading with Infiles */
for (int i = 0; i < Infiles.size(); ++i){
delete Infiles[i]; // this part crashes
Infiles[i] = NULL;
}
But the line delete Infiles[i]; causes crashes, what is wrong with my code?

Yes, you are absolutely correct. Deleting through a pointer makes all pointers referencing the deleted object invalid. And the best way to avoid problems like this is to stop using owning pointers in C++ code.
By the way, this fact is the best reason not to set pointers to nullptr after deleting them - since it does nothing to other copies of the same pointer, it does not make the code any safer.

Related

how can i hold pointer object in array? [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 1 year ago.
Improve this question
I'm a newbie. since my code is so long I can't edit it for being reproducible so I will show you what I did in a simple way
I have a Team class. I want to hold all my objects in an array so that I can reach them somewhere else and map for some data.
so I did a function basically doing this (exactly this part b[1] = a;)
int* a; // represent my object
int *b = new int[2]; //represent my static object pointer
b[1] = a;
error saying cant assign int = *int
yes absolutely true but I have to hold my object in the array. and I thought this could work but no... is there a way to hold an object in an array or can I say give me space for *int, during pointer initializing?
A better way would be to use std::vector to hold your class objects. The advantage of using a std::vector is that then you won't have to deal with memory management explicitly. vector will take care of it.
In addition, i will also recommend using smart pointers.
To solve your error above you can use the following example:
int i = 0, j = 0;//int objects
int* p = &i, *q = &j; //pointer to int objects
int **b = new int*[2]; //note i have added * on both the left and right hand side.
b[0] = p;
b[1] = q;
//dont forget to use delete below
Note you should use std::vector and smart pointers, but i have added an example so that you can see how to remove the error and use this example as a reference.

Program wont move past delete [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 3 years ago.
Improve this question
So I can not figure out why my program halts at the delete statement inside my purge loop. It's not crashing it just won't execute or give my any sort of error.
I have double checked that I am deleting an array and need the brackets, and verified that it is valid new memory. It will not work if its called by the destructor or explicitly
int main()
{
darray DA1;
DA1.Add("Hello");
DA1.Add("Good Morning");
return 0;
}
void Add(const char * string)
{
char ** temp = new char *[m_count + 1];
for (int i = 0; i < m_count; ++i)
temp[i] = m_array[i];
temp[m_count] = new char[strlen(string)];
strcpy(temp[m_count], string);
delete[] m_array;
m_array = temp;
m_count++;
}
void Purge()
{
for (int i = 0; i < m_count; ++i)
{
delete [] m_array[i];
m_array[i] = nullptr;
}
delete[] m_array;
m_array = nullptr;
m_count = 0;
}
I expect it to go through the 2d dynamic array deleting each array and then delete the final array.
These lines contain an error:
temp[m_count] = new char[strlen(string)];
strcpy(temp[m_count], string);
... in that you allocate strlen(string) bytes, but neglect to allocate the extra byte required for the NUL terminator required at the end of the string. Thus your strcpy() command writes one byte past the end of your allocated array, invoking undefined behavior. You can correct it by changing it to this:
temp[m_count] = new char[strlen(string)+1];
strcpy(temp[m_count], string);
One separate note: manually managing heap-allocations this way is very difficult to get right, even for experienced programmers, so unless you are writing this program as an exercise in order to learn how to manually-manage heap-allocation, I highly recommend using std::string (or some similar string-class) instead of C-style char-arrays. You will save yourself a lot of unnecessary pain. (In fact, I think a std::vector<std::string> would provide you with all the functionality you are trying to implement here)

c++ copy object to pointer array [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 3 years ago.
Improve this question
I have a pointer array of Word (objects) and I have to assign another object of type Word to this objects array.
Using this two lines of code I put the new object w inside my objects array (word).
Word w = Word(new_word, len);
this->word[index - 1] = w;
Then I print my objects array and everything comes out right
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 1
After "End of function" we return to the main class that call to another function.
This function print the objects array again but now the function does not print the w object that I insert in the previous function.
Second function
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 2
Can anyone explain to me why this is happening and how it can be arranged.
Though it's difficult to be certain (since we don't have the rest of the function to look at), it seems that you may have a dangling pointer issue.
When you declare Word w = Word(new_word, len); in your function, you're declaring it as a local variable, placing it on the stack. Adding this to the array doesn't cause any issues when you're still in the function, but once you return from where you came, the function's memory - including Word w - is destroyed. When you try to access that memory location again by printing it from the array, you're looking for a variable that no longer exists, and thus get undefined behavior.
Luckily, you're using c++, and heap memory management is fairly well supported! I would consider implementing word as an array of pointers. If you then try something like this...
Word *w = new Word(new_word, len); //use "new" to create an object on the heap - persistent after you leave the function!
this->word[index - 1] = w; //make sure this->word is now an array of Word*; it seems to currently be an array of Word
...you may find the problem solved. Just don't forget to free it when you're done!

Getting Array from Another class C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am making a simple Lottery program - and am struggling with implementation. I have a class called 'Ticket Line' this class simply holds 6 numbers that the player is playing a lottery for.
What I want to do, is generate 6 randomly (got function for this already) and then store that in another class as values. To do this, I am using the following code:
class Draw
{
private:
int drawID;
TicketLine* DrawnNumbers;
bool drawn;
}
When a Draw is completed I want to generate the Random Numbers ( from the TicketLine class) and then for the Draw to be able to store those numbers into its Draw File.
How would I be able to access the functionality of the DrawnNumbers class - and store the results from the getTicketNumbers.getTicketLine()function.
int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();};
The program crashes the following code:
//int *ptr[6] = getTicketNumbers();
int *ptr[6] = getTicketNumbers();
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
TicketLine class:
private:
int select[6]; //Array of Ticket Numbers.
int* getTicketLine(void) { return select; };
I am willing to offer a couple of virtual beers to the solution. I am as yet to find a good online pub - if you know of one then please do let me know :-)
Thanks,
Without knowing any more, this line:
int *ptr[6] = getTicketNumbers();
is very suspect.
Why? Well, we haven't seen the implementation of getTicketNumbers so we don't know if it's actually allocating memory for 6 and returning such an array.
Also, you are printing the values of pointers here:
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
Where, if you intended to actually print the int values, you'd say something like this:
for (int x = 0; x < 6; x++){
cout << *(ptr[x]);
}
My guess is that you are either:
Going out of bounds of an array that was (not) allocated, or,
Modifying actual pointer values somewhere instead of the integers they point to (as indicated by your lack of dereferencing ptr[x] in your print statement)
Edit
With more information, it seems you probably meant to say this:
int *ptr = getTicketNumbers();
instead of this:
int *ptr[6] = getTicketNumbers();
You should probably be doing some sanity checks as well to make sure that select is actually filled before calling that function (maybe giving it a default value of {0,0,0,0,0,0} in the constructor)
DrawnNumbers doesn't appear to be pointing to anything yet. It's a pointer, but to what?
Also, be careful about returning arrays that way. If the object or stack frame that the array resides in goes away, you'll be left pointing to bad things.

C++ How to resize a dynamic array without losing data? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to resize a dynamic array without losing data.
Like this:
double * pVecDin;//POINTER
int num_values = 2;
pVecDin = new double[num_values];
pVecDin[0]=5;
pVecDin[1]=6;
int new_num_values=4;
pVecDin = new double[new_num_values];
//Next I lost value of pVecDin[0] and pVecDin[1]
pVecDin[2]=8;
pVecDin[3]=9;
Do I need make an Auxiliar Dynamic Array to copy the old values?
Like:
int new_num_values=4;
double * pVecDin_aux; //POINTER
pVecDin_aux = new double[new_num_values];
pVecDin_aux = pVecDin;
for(int i=0; i < n; i++)
{
pVecDin_aux[i] = pVecDin[i];
}
Make a new, empty array with the new desired size.
Copy everything in the old array to the new array.
Delete the old array.
Assign the pointer of the old array to the address of the new array.
Or use a vector.
As nhgrif has mentioned, you need to make copy of the array.
There is another way if you can use malloc for memory allocation, then you can use realloc for resizing the array.
There are better ways as suggested by other like to use std::vector or list.