473,322 Members | 1,496 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Calling new pointer twice?

My question is,this code is valid or not? can this code cause memory
leaks?

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{

int * num = new int(12);
num = new int(18);

cout << *num;

delete num;

return 0;
}

Feb 6 '06 #1
13 2872
morz <bl*********@gmail.com> wrote:
My question is,this code is valid or not?
It is valid.
can this code cause memory
leaks?
Yes, it definitely is a memory leak.
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{

int * num = new int(12);
num = new int(18);
At this point, the old value of 'num' is lost, so you are never able
to free it. Tho valid, you have a memory leak, which is why you should
always avoid this kind of code.

cout << *num;

delete num;

return 0;
}


regards
--
jb

(reply address in rot13, unscramble first)
Feb 6 '06 #2
ok i change my code.How about below code? still can cause memory leak
or not? btw,thank you Jakob Bieling. :)

#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{
auto_ptr<int> num(new int(12));
num.reset(new int(18));

cout << *num;

return 0;
}

Feb 6 '06 #3
morz <bl*********@gmail.com> wrote:
ok i change my code.How about below code? still can cause memory leak
or not? btw,thank you Jakob Bieling. :)

#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{
auto_ptr<int> num(new int(12));
num.reset(new int(18));

cout << *num;

return 0;
}


No, now you do not have a memory leak, because calling reset will
take care of freeing the memory, if necessary.

hth
--
jb

(reply address in rot13, unscramble first)
Feb 6 '06 #4
good,like i thougt... if i create two dimensional array like this....

#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{

auto_ptr<int> *num;

num = new auto_ptr<int>[2];

for(int i=0;i<2;i++){
num[i].reset(new int(i+10));
}

for(int i=0;i<2;i++){
cout << *num[i] << endl;
}

// Should i include delete below?

//*********************************************
delete num;
//*********************************************

return 0;
}

if i my code wrong and i don't want to include delete num,how to change
my auto_ptr?

Feb 6 '06 #5
morz wrote:
good,like i thougt... if i create two dimensional array like this....

#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{

auto_ptr<int> *num;

num = new auto_ptr<int>[2];

for(int i=0;i<2;i++){
num[i].reset(new int(i+10));
}

for(int i=0;i<2;i++){
cout << *num[i] << endl;
}

// Should i include delete below?

//*********************************************
delete num;
//*********************************************

return 0;
}

if i my code wrong and i don't want to include delete num,how to change
my auto_ptr?


1. You should delete num as you wrote.

2. I can't see how num is a two dimensional array. It is just an array
of two auto_ptr<int>'s each points to an int. All in all you have two
ints, in a single dimension.

3. You are new-ing and delete-ing num in the same scope. Why bother
using dynamic memory? Stack allocate the objects will be more appropriate.

4. auto_ptr<> is not for creating arrays. While your code is all right,
it is better to use container classes like vector<>, deque<> and stack<>
to do the job.

Ben
Feb 6 '06 #6
morz <bl*********@gmail.com> wrote:
good,like i thougt... if i create two dimensional array like this....
Think about it. You are only creating a one-dimensional array.
#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{

auto_ptr<int> *num;

num = new auto_ptr<int>[2];

for(int i=0;i<2;i++){
num[i].reset(new int(i+10));
}

for(int i=0;i<2;i++){
cout << *num[i] << endl;
}

// Should i include delete below?
Yes. The rule of thumb is, call delete for every time you called
new. When using an auto_ptr (or some other smart pointer), this rule of
thumb is still valid, tho less obvious: when using auto_ptr, the
auto_ptr takes care of deleting, so everything is fine. But for num, you
still have to take care of deleting yourself!
//*********************************************
delete num;
//*********************************************
Another rule: *Never* call 'delete', when you allocated with
'new[]'. And also never call 'delete[]' when you allocated with 'new'.
new[]/delete[] is one pair and new/delete is another. Do not mix them
up. You should have written:

delete [] num;
return 0;
}

if i my code wrong and i don't want to include delete num,how to
change my auto_ptr?


It depends on the problem. If you also did not want to include
'delete [] num', then it seems like your problem would be better solved
with just a vector of ints:

std::vector <int> num;

If you are coming from Java, you will probably be tempted to use
'new' and 'new[]' often. In most cases, you do not need dynamic memory
allocation using new/new[], because the language gives you other, safer
tools to work with.

hth
--
jb

(reply address in rot13, unscramble first)
Feb 6 '06 #7
ok..i change my code again..how about code below? any memory leak?

#include <cstdlib>
#include <iostream>
#include <memory>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
int * num;

vector<int*> test;
for(int i=0;i<5;i++)
{
num = new int(i+10);
test.push_back(num);
}

for(int i=0;i<5;i++)
{
cout << *test[i] << endl;
}

for(int i=0;i<test.size();i++)
delete test[i];

system("pause");

return 0;
}

Feb 6 '06 #8
morz <bl*********@gmail.com> wrote:
ok..i change my code again..how about code below? any memory leak?
No memory leak, but consider the following modifications (where the
comments are):
#include <cstdlib>
#include <iostream>
#include <memory>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
// int * num;
// vector of ints now vector<int> test;
for(int i=0;i<5;i++)
{
// num = new int(i+10);
test.push_back(i + 10); // push the int
}

for(int i=0;i<5;i++)
{
cout << test[i] << endl; // no deref necessary
}
// no need to delete anything .. the vector
// takes care of everything // for(int i=0;i<test.size();i++)
// delete test[i];

system("pause");

return 0;
}


hth
--
jb

(reply address in rot13, unscramble first)
Feb 6 '06 #9
Thank you Jakob Bieling for your reply.Actually my purpose i'm using
pointer in this example is to get some idea with my application i'm
building now.

one last question.. if i stick wih my old code(using pointer in
vector),instead i do like this :

for(int i=0;i<test.size();i++)
delete test[i].;

can i do like this :

for(int i=0;i<test.size();i++)
test[i].pop_back();

or

test.clear();

are this vector 'pop_back' and 'clear' method really delete and clear
memory? no memory leaks?

Feb 6 '06 #10
morz <bl*********@gmail.com> wrote:
Thank you Jakob Bieling for your reply.Actually my purpose i'm using
pointer in this example is to get some idea with my application i'm
building now.

one last question.. if i stick wih my old code(using pointer in
vector),instead i do like this :

for(int i=0;i<test.size();i++)
delete test[i].;

can i do like this :

for(int i=0;i<test.size();i++)
test[i].pop_back();

or

test.clear();

are this vector 'pop_back' and 'clear' method really delete and clear
memory? no memory leaks?


No, they do not delete anything. They just remove the *values* they
have stored. In your particular case, they will remove pointers, but not
the memory that those pointers point to (because the vector cannot know
anything about those pointers .. they might all point to the same int or
... you get the point).

In other words, this will give you memory leaks. The vector and its
contents will automatically be freed, meaning the memory needed for your
pointers will be freed. What the pointers point to still needs to be
freed by you.

hth
--
jb

(reply address in rot13, unscramble first)
Feb 6 '06 #11
benben <be******@yahoo.com.au> wrote in
news:43**********************@news.optusnet.com.au :
morz wrote:
good,like i thougt... if i create two dimensional array like this....

#include <cstdlib>
#include <iostream>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{

auto_ptr<int> *num;

num = new auto_ptr<int>[2];

for(int i=0;i<2;i++){
num[i].reset(new int(i+10));
}

for(int i=0;i<2;i++){
cout << *num[i] << endl;
}

// Should i include delete below?

//*********************************************
delete num;
//*********************************************

return 0;
}

if i my code wrong and i don't want to include delete num,how to
change my auto_ptr?

1. You should delete num as you wrote.


No, you should:

delete[] num;

Leaving it as written is Undefined Behaviour.
2. I can't see how num is a two dimensional array. It is just an array
of two auto_ptr<int>'s each points to an int. All in all you have two
ints, in a single dimension.

3. You are new-ing and delete-ing num in the same scope. Why bother
using dynamic memory? Stack allocate the objects will be more
appropriate.

4. auto_ptr<> is not for creating arrays. While your code is all
right, it is better to use container classes like vector<>, deque<>
and stack<> to do the job.


No, it's not alright. new must be matched with delete, and new[] must be
matched with delete[].
Feb 6 '06 #12
good answer from Jakob Bieling and Andre Kostur.Thank you.

Feb 6 '06 #13
morz wrote:
My question is,this code is valid or not? can this code cause memory
leaks?

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{

int * num = new int(12);
num = new int(18); You have just created a memory lead -- the initial value of num is lost,
you have no way of delete-ing the memory allocated by "new int(12)".
cout << *num; I believe the unflushed cout is either implementation defined behavior
or UB. I may, however be wrong.
delete num;

return 0;
}

Feb 6 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: johny smith | last post by:
I am trying to figure out a way to print the address of what called a certain function once inside the function. I am assuming that this information is on the stack somewhere. But can someone...
4
by: Venn Syii | last post by:
I've searched all the forums but cannot find an answer to this question. I do the following: vector<MyClass*> myClassList; Later in the program I try to add to myClassList with a...
1
by: neha | last post by:
i want to know details about 'this' pointer using in C++ if anyone knows please inform me at my e-mail id My id is jsudesh@gmail.com thanks
6
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void*...
12
by: st_ev_fe | last post by:
I've noticed that when constructing a subclass, the base class get's it's contructors called. Is there some way to avoid this? The base class has one variable, which gets initialised to 0. ...
13
by: santosh | last post by:
Hi, If I call free() with a uninitialised pointer, will the program state become undefined, or will free() return harmlessly? Incidentally, is there a way in Standard C to determine weather a...
49
by: elmar | last post by:
Hi Clers, If I look at my ~200000 lines of C code programmed over the past 15 years, there is one annoying thing in this smart language, which somehow reduces the 'beauty' of the source code...
2
by: Geler | last post by:
A theoretical question: Sorry if its a beginner question. Here is a quote from the MSDN explaning the C/C++ calling convention.. It demonstrates that the calling function is responsible to clean...
15
by: Sampat | last post by:
Hi, I wanted to know the performance of calling a function pointer v/s a normal function call in javascript in a scenario where there are multiple calls in the js to the same function. Please...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.