473,786 Members | 2,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

allocating array in function



Hi

I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:
class cssReader
{
public:
cssReader();
cssReader(strin g, string);
~cssReader();

public:

int* GetWandRead(str ing, int);

public:
int *d;

.....'...

}

int* cssReader::GetW andRead(string dirname, int rows)
{
.....
d = new int[duration*(int)s amprate];

// varibles duration and samprate are changing
// thats why I have to dynamically allocate my 'd'.
.....

return d;

}
using the above:
int *data;
ccReader *css = new cssReader;
void getData()
{

....
....
data = css->GetWandRead(di rname, rows);

// plot data

delete [] data;
}
first sorry for the short version of the code. It was thought
non essential.

The above sometimes works and most of the time doesn't. If I
remove the last 'delete' statement it works but having large
amount of data the memory leak is huge.
I guess my question is: Is it ok to allocate an array inside
a function, delete it outside the function and reallocate
and delete and reallocate and delete ...
Thanks in advance

H.

Jul 23 '05 #1
5 1927
What do you mean "doesn't work"?
If you mean that the allocated memory can't be freed every time in a loop, I
guess your coding has some problem to forget free the array.

Memory (including array) could be allocated(new or malloc) in one place, and
freed in other place because it's located in heap.

"Henrietta Denoue" <he*******@netc alcul.fr> wrote in message
news:d1******** **@dolly.uninet t.no...


Hi

I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:
class cssReader
{
public:
cssReader();
cssReader(strin g, string);
~cssReader();

public:

int* GetWandRead(str ing, int);

public:
int *d;

....'...

}

int* cssReader::GetW andRead(string dirname, int rows)
{
....
d = new int[duration*(int)s amprate];

// varibles duration and samprate are changing
// thats why I have to dynamically allocate my 'd'.
....

return d;

}
using the above:
int *data;
ccReader *css = new cssReader;
void getData()
{

...
...
data = css->GetWandRead(di rname, rows);

// plot data

delete [] data;
}
first sorry for the short version of the code. It was thought
non essential.

The above sometimes works and most of the time doesn't. If I
remove the last 'delete' statement it works but having large
amount of data the memory leak is huge.
I guess my question is: Is it ok to allocate an array inside
a function, delete it outside the function and reallocate
and delete and reallocate and delete ...
Thanks in advance

H.

Jul 23 '05 #2
Henrietta Denoue wrote:


Hi

I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:
class cssReader
{
public:
cssReader();
cssReader(strin g, string);
~cssReader();

public:

int* GetWandRead(str ing, int);

public:
int *d;

....'...

}

int* cssReader::GetW andRead(string dirname, int rows)
{
....
d = new int[duration*(int)s amprate];

// varibles duration and samprate are changing
// thats why I have to dynamically allocate my 'd'.
....

return d;

}
using the above:
int *data;
ccReader *css = new cssReader;
void getData()
{

...
...
data = css->GetWandRead(di rname, rows);

// plot data

delete [] data;
}
first sorry for the short version of the code. It was thought
non essential.

The above sometimes works and most of the time doesn't.
What do you mean by that? How does it not work? What does it do instead?
If I remove the last 'delete' statement it works but having large
amount of data the memory leak is huge.
I guess my question is: Is it ok to allocate an array inside
a function, delete it outside the function and reallocate
and delete and reallocate and delete ...


Yes, it is. One possible reason for problems is that you don't obey the Rule
of Three. If you need one of a copy constructor, assignment operator or
destructor, you almost certainly need all three of them. If you happen to
copy one of your cssReader objects anywhere in your program, you'll get
nasty double deletion errors.

Jul 23 '05 #3
The fact that d is a class member instead of a local variable to
GetWandRead raises a red flag to me... Is d used anywhere else? And if
not, does the problem go away if you make it a local variable?

I don't really see any reason why it shouldn't work to tell you the
truth. I'm not a C++ guru or anything, but I'm pretty sure that what
you have should work. So I suspect the problem is somewhere else.

Jul 23 '05 #4
Henrietta Denoue <he*******@netc alcul.fr> wrote in message news:<d1******* ***@dolly.unine tt.no>...
Hi

I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:
first sorry for the short version of the code. It was thought
non essential.

The above sometimes works and most of the time doesn't. If I
remove the last 'delete' statement it works but having large
amount of data the memory leak is huge.
I guess my question is: Is it ok to allocate an array inside
a function, delete it outside the function and reallocate
and delete and reallocate and delete ...
Thanks in advance

H.


One Question.
I just want to know whether your app is multithread apps or not?
If it is, Due to the fact that your GetData function is not thread-safe
function. It could be crashed.

Regards,
Jul 23 '05 #5
Henrietta Denoue wrote:

Hi

I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:

class cssReader
{
public:
cssReader();
cssReader(strin g, string);
~cssReader();
What does the destructor do?
Does it delete[] the allocated memory?

int *data;
ccReader *css = new cssReader;
void getData()
{

...
...

data = css->GetWandRead(di rname, rows);

// plot data

delete [] data;


That's not a good idea.
You should get into the habit of:
"The object (or function) that allocated the data is
reponsible for freeing it."

That's a simple rule and there are exceptions to it, but as a rule
of thumb it works pretty well. In your example it means, since the
cssReader object allocated the memory, it is responsible for deleting
it. Not the code that created the cssReader object, not some obscure
function, nothing else but the cssReader object itself. If you keep
the code environment dealing with managing that memory small, it is much
easier to find bugs and code correctly as if some function allocates some
memory and 15000 lines of code later in some other function the deallocation
happens.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #6

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

Similar topics

6
4128
by: soni29 | last post by:
hi, i'm reading a c++ book and noticed that the author seems to allocate memory differently when using classes, he writes: (assuming a class called CBox exists, with member function size()): // first way CBox x; x.size(); // second way
3
2181
by: Erik S. Bartul | last post by:
lets say i want to fill up a multidimentional array, but i wish to allocate memory for it on the fly. i assume i declare, char **a; but how do i allocate memory for the pointers, so i can then allocate to the pointers to which those pointers point? essentially lets say i during runtime deturmine i must allocate space for 60
15
6735
by: fix | last post by:
Hi all, I am writing a program using some structs, it is not running and I believe it is because there's some memory leak - the debugger tells me that the code causes the problem is in the malloc function. Is there any general rules that tell me when to allocate memory? I thought I don't have to if it is a variable that's not a pointer, and I have to if it is. I am a bit confused about the arrays particularly. In normal situations,...
5
3678
by: Johnathan Doe | last post by:
Why is is necessary to write a function that allocates memory for, or changes, a pointer to a char array using char** instead of char*? E.g. void modify_string( char** string ) { if( string == NULL ) return;
10
2594
by: junky_fellow | last post by:
What is the correct way of dynamically allocating a 2d array ? I am doing it the following way. Is this correct ? #include <stdlib.h> int main(void) { int (*arr)(3); arr = malloc(sizeof(*arr) * 4); /* I want to dynamically allocate
1
1432
by: Peter Oliphant | last post by:
I'm using VS C++.NET 2005 Express in /clr mode. Say I have a PointF array: array<PointF>^ point_array = gcnew array<PointF>(100) ; Now I want to re-allocate point_array, and in doing so also free up the previous array's points. Is this sufficient: point_array = gcnew array<PointF>(999) ; // new array or do I need to tell the system I'm doing this, ala something like:
4
2981
by: Rakesh Kumar | last post by:
Hi All - In a project of mine - I was trying to scale down the actual issue to the following piece of code. I need to allocate an array of strings and reserve the individual string to a particular size (4K) . I wrote 2 functions - allocVectorOfStrings() and allocArrayOfStrings(). Each of them seem to allocate similar amounts of memory - but the version of vectorOfStrings seem to crash with the following error - "double free or corruption...
6
5186
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t = malloc(n*sizeof(r)) and (to a degree) by the surrounding error checking.
13
1999
by: charlie | last post by:
I came up with this idiom for cases where a function needs a variable amount of memory for it's temporary storage so as to avoid constantly mallocing. It makes me feel a little uncomfortable to have unfreeable (but still technically reachable) memory hanging around but it is, I think still a useful thing to do: void fn(int *stuff, int nstuffs) { static int *temp_stuff = NULL; static int ntemp_stuffs = 0;
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10108
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9960
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4064
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.