473,770 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Where to allocate memory for the char * data member ...

I have created class definition which contains
a charater pointer as one of it's data memeber.

The objective is to read some data from a file,
and assign it to a data member;

Size of data is not known in the begining.
We can assume that it will not exceed 256;

class definition:

class abc {
private:
char * temp;
short int size;
public:

abc() {
size = 0;
temp = new char [size + 1];
};

~abc() {
delete temp;
};

friend istream& operator >>(istream &is, abc & obj);
char * Get_temp() {
return temp;
};
};

istream& operator >> (istream & is, abc &obj)
{
is >> obj.temp;
return is;
}

int main ()
{
abc object_abc;

ifstream infile("xyz.txt ");
assert(infile);
assert(infile.i s_open());

while (!infile.eof()) {
infile >> object_abc;
cout << object_abc.Get_ temp() << endl;
}

infile.close();

return 0;
}

My question is how, when, and where to allocate memory for the data
member "temp".

Dec 30 '05 #1
4 5002
ma****@gmail.co m wrote:
My question is how, when, and where to allocate memory for the data
member "temp".


First of all, in your destructor, use delete[] rather than delete.
Otherwise you get a memory leak.

Now, on to your question. You've got a bit of a problem here, in that
your use of a naked array, with no bounds checking, is very much
unsafe. However big you make the array, if your input file is one byte
longer, you will get undefined behavior.

If you *really* want to accept an istream into your array, you should
look into stream manipulators. You could adopt a strategy whereby the
stream manipulator allocates more memory just before you need it.

Still, I'd avoid that altogether and just use a std::stringstre am or
something. There's basically no good reason to use char* instead of
std::string, generally. And exposing a pointer to your internal
representation, especially a pointer to non-const, is just asking for
trouble (and no, a pointer to const isn't sufficient for safety -- they
can still delete it, for one thing).

Defensive programming is your friend.

Oh, and if you're absolutely sure about that 256 byte limit, and you
aren't making tons of these things, maybe just statically allocate an
array of size 256, rather than worrying about doing it dynamically.
But again... by the time you're doing that, you're already a good ways
down the path to perdition.

Luke

Dec 30 '05 #2
ma****@gmail.co m wrote:
I have created class definition which contains
a charater pointer as one of it's data memeber.
The problems you are having and more are avoided if you
use an already designed and debugged class rather than
char*. If the object is a string, use the std::string
class. If it's an array of char, use vector.
short int size;
Why short?
abc() {
size = 0;
temp = new char [size + 1];
};
Why are you allocating one additional byte? Why is size zero.
~abc() {
delete temp;
Wrong delete. If you new[], you must do
delete [] temp;
You also have a rule of three violation. Your object will blow
up if copied or assigned. You need to do a copy constructor and
a copy assignment operator. Again this wouldn't be a problem if
temp were a vector or string. These classes already have these defined.

ifstream infile("xyz.txt ");
assert(infile);
assert(infile.i s_open());
Assert is a lousy way of detecting errors. These two tests are
redundant as well.
while (!infile.eof()) {
This is NOT the way to check for end of file. The eof state is
only set AFTER a read fails.

while(infile >> object_abc) {

will do what you want (it will fail when there is an error or eof, you
can then check the eof flag if you need to differentiate).


My question is how, when, and where to allocate memory for the data
member "temp".


You haven't told us how you know what the data is that you are reading?
What is the nature of the file?

You can't use a >> char* without knowing some upper bound on the length.
This isn't a limitation with the string class though.

As a matter of fact, I think you can probably deep-six your entire class:

int main() {
ifstring infile("xyz.txt ");
if(!infile) return EXIT_FAILURE;

std::string abc;
while(infile >> abc) {
cout << abc << "\n";
// if you really wanted a char* out of it, you can use abc.c_str()
}
cout << flush;
}

Dec 30 '05 #3
> short int size;
1. Why short? <<--- I know the size will not be greator than 256

2a. Why are you allocating one additional byte? <<--- I think I should
have initialilzed the data member "temp" to NULL.

2b. Why is size zero. <<-- Just initializing this to a value

"You also have a rule of three violation. Your object will blow
up if copied or assigned. You need to do a copy constructor and
a copy assignment operator. Again this wouldn't be a problem if
temp were a vector or string. These classes already have these
defined."

Yeap, can't do without the copy and assignment constructor.

3. Yeap! delete [] temp; <--- missed this one.

"This is NOT the way to check for end of file. The eof state is
only set AFTER a read fails.

while(infile >> object_abc) {

will do what you want (it will fail when there is an error or eof, you
can then check the eof flag if you need to differentiate). "

.... hmm ... I have to make a note of this one.

+++++++++++++++ +++++++++++++++ +++++++++++++++ +++++++++
You haven't told us how you know what the data is that you are reading?
What is the nature of the file? You can't use a >> char* without knowing some upper bound on the length.
This isn't a limitation with the string class though.


I could have used string type for the data members.
However, I didn't want the overhead that comes with the string class.

A sample data file, would be as follows

xyz.txt
some_name1 value1
some_name2 value2
..
..

Having said that my class definition needs two different data members,
i didn't include that in my previous post.

class abc {
....
char * temp;
char * temp2;
....
};

Other functions will definitely require amendments, and will
incorporate the second data member.
istream& operator >> (istream & is, abc &obj)
{
is >> obj.temp >> obj.temp2;
return is;
}

I really do appreciate your suggestion, besides using another class
string or stringstream, if I stick with "char *"
I am still not sure how, when, and where to allocate memory for "temp
and temp2" data members.

Regards,
Manish

Dec 30 '05 #4
> class abc {
....
char * temp;
char * temp2;
....
};

Other functions will definitely require amendments, and will
incorporate the second data member.
istream& operator >> (istream & is, abc &obj)
{
is >> obj.temp >> obj.temp2;
return is;
}

I really do appreciate your suggestion, besides using another class
string or stringstream, if I stick with "char *"
I am still not sure how, when, and where to allocate memory for "temp
and temp2" data members.


Since you don't know the size you are reading before you read it, and since
you don't want to use std::string, there is only one logical place to
allocate the memory for temp and temp2, in the class constructor. Delete
them in the class destructor.

That fixes the When and Where, the how is simple and you already know how to
use new.


Jan 2 '06 #5

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

Similar topics

2
2423
by: CoolPint | last post by:
Standard exception classes in C++ have what() which returns const char * and they have constructors accepting string. Where is that string created and when is the string destroyed? In the function below, e is a local object so when the function terminates, the internal string should be gone too, isn't it?
17
5052
by: Jonas Rundberg | last post by:
Hi I just started with c++ and I'm a little bit confused where stuff go... Assume we have a class: class test { private: int arr; };
5
1777
by: August1 | last post by:
This is a short program that I have written from a text that demonstrates a class object variable created on the stack memory and another class object variable created on the heap memory. By way of the text, the program is supposed to demonstrate the use of a copy constructor function for the object created on the heap (because there is a char* pointer variable in the instantiated class) and how you would use the delete keyword with the...
12
5636
by: gc | last post by:
I am writing a function that given nx1 vector a and a nx1 b solves a system of equations f(a,c)=b for a nx1 c. While writing the function: 1] Should I allocate the memory for c within the function and return the allocated memory? something that leads to double *solve(const double *a,const double *b,int n) { double *c;
6
2373
by: Peter Hickman | last post by:
I have a program that requires x strings all of y length. x will be in the range of 100-10000 whereas the strings will all be < 200 each. This does not need to be grown once it has been created. Should I allocate x strings of y length or should I allocate a single string x * y long? Which would be more efficient and / or portable? Thank you.
14
2641
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
5
1789
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
17
9148
by: dtschoepe | last post by:
Hi, I have a homework project I am working on, so be forwarned, I'm new to C programming. But anyway, having some trouble with a memory allocation issue related to a char * that is a variable inside of a structure. I keep getting segmentation fault errors and I am having trouble understanding why. Here's the parts of the code in question... This is part of the .h file where the struct us defined...
68
2694
by: DaveJ | last post by:
Recently I was working on a project where I came across an issue where the program cored and reported "free(): invalid pointer". I found a resolution for this, but don't fully understand why the issue occurred in the first place. The project uses a simple template class that acts as a buffer. Initially it has a fixed length, but it's append methods will extend the size of the buffer if necessary. Another class defines a struct, that...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
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
9906
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
7456
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
5354
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...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.