473,698 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Design question: using malloc?

Hello,

I'm quite new to C++ and have some base C knowledge. So I know how to
solve a given problem, by I sometimes tend to fall back to C. That is
what I want to avoid in my current project. Therefore I have the
following question:

I maintain a list of objects that are created. There is some information
that is logically related to each instance. I encapulate this in a
struct like this:

struct myListEntry {
myObject entry;
int relatedData;
}

What is the ideal way to implement adding another object to the vector?
(myVector has type vector<myListEn try> in this example)
Should I use malloc to reserve memory for my struct?
Should I do the following?
...
myListEntry newEntry;
newEntry.entry = something;
newEntry.relate dData = something_else;
myVector.push_b ack(newEntry);
...
Or is there another preferred way?

Regards,
Christof Krueger

Jul 22 '05 #1
10 2267
"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...
Hello,

I'm quite new to C++ and have some base C knowledge. So I know how to
solve a given problem, by I sometimes tend to fall back to C. That is
what I want to avoid in my current project. Therefore I have the
following question:

I maintain a list of objects that are created. There is some information
that is logically related to each instance. I encapulate this in a
struct like this:

struct myListEntry {
myObject entry;
int relatedData;
}

What is the ideal way to implement adding another object to the vector?
(myVector has type vector<myListEn try> in this example)
Should I use malloc to reserve memory for my struct?
Should I do the following?
...
myListEntry newEntry;
newEntry.entry = something;
newEntry.relate dData = something_else;
myVector.push_b ack(newEntry);
...
Or is there another preferred way?

Regards,
Christof Krueger


std::vector (and STL containers in general) allocate memory internally as
required. In this instance, your call to 'push_back' results in a copy of
the argument being stored in the vector. vector allocates memory for
the object and uses either a copy constructor or assignment operator to
initialize it.

An object stored in a container must at the minimum be 'Assignable'
which generally means that it has a copy constructor and an assignment
operator (if it is a simple type or a combination of simple types these are
not always required).

If you add these to your struct:

struct myListEntry {
myListEntry(con st myObject& obj, const int& n)
: entry(obj), relatedData(n) {}
myListEntry & operator = (const myListEntry &rhs)
{
entry = rhs.entry;
relatedData = rhs.relatedData ;
return *this;
}
myObject entry;
int relatedData;
}

then not only will the code you provided be fine but you could also write:

myVector.push_b ack(myListEntry (something, something_else) );

Tom
Jul 22 '05 #2
> If you add these to your struct:

struct myListEntry {
myListEntry(con st myObject& obj, const int& n)
: entry(obj), relatedData(n) {}
myListEntry & operator = (const myListEntry &rhs)
{
entry = rhs.entry;
relatedData = rhs.relatedData ;
return *this;
}
myObject entry;
int relatedData;
}

then not only will the code you provided be fine but you could also write:

myVector.push_b ack(myListEntry (something, something_else) );


I just had to check 3 books (without result) and then search the web to
find out the difference between struct and class in C++ in detail. Seems
that the only difference is that in a class the default visibility is
private and in a struct it is public. Good to know :)

Thank you very much for your help, Thomas!

The conclusion is: Dealing with malloc/free in C++ too much (or even at
all?!?) is not a good idea and should be avoided by using save
components from STL. Is that right?

Bye,
Christof

Jul 22 '05 #3
On Mon, 15 Dec 2003 00:48:29 +0100 in comp.lang.c++, Christof Krueger
<ne**@pop2wap.n et> was alleged to have written:
I just had to check 3 books (without result) and then search the web to
find out the difference between struct and class in C++ in detail. Seems
that the only difference is that in a class the default visibility is
private and in a struct it is public. Good to know :)
This issue is covered in question "[7.8] What's the difference between the
keywords struct and class?" of Marshall Cline's C++ FAQ. You can get the
FAQ at: http://www.parashift.com/cpp-faq-lite/
The conclusion is: Dealing with malloc/free in C++ too much (or even at
all?!?) is not a good idea and should be avoided by using save
components from STL. Is that right?


Short answer: yes.

Jul 22 '05 #4

"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...
If you add these to your struct:

struct myListEntry {
myListEntry(con st myObject& obj, const int& n)
: entry(obj), relatedData(n) {}
myListEntry & operator = (const myListEntry &rhs)
{
entry = rhs.entry;
relatedData = rhs.relatedData ;
return *this;
}
myObject entry;
int relatedData;
}

then not only will the code you provided be fine but you could also write:
myVector.push_b ack(myListEntry (something, something_else) );


I just had to check 3 books (without result) and then search the web to
find out the difference between struct and class in C++ in detail. Seems
that the only difference is that in a class the default visibility is
private and in a struct it is public. Good to know :)

Thank you very much for your help, Thomas!

The conclusion is: Dealing with malloc/free in C++ too much (or even at
all?!?) is not a good idea and should be avoided by using save
components from STL. Is that right?

Bye,
Christof

I just wanted to add that TTBOMK the 'new' and 'delete' operators are
the c++ way to allocate and free memory

someone else
Jul 22 '05 #5
David Harmon wrote:
On Mon, 15 Dec 2003 00:48:29 +0100 in comp.lang.c++, Christof Krueger
<ne**@pop2wap.n et> was alleged to have written:
I just had to check 3 books (without result) and then search the web to
find out the difference between struct and class in C++ in detail. Seems
that the only difference is that in a class the default visibility is
private and in a struct it is public. Good to know :)

This issue is covered in question "[7.8] What's the difference between the
keywords struct and class?" of Marshall Cline's C++ FAQ. You can get the
FAQ at: http://www.parashift.com/cpp-faq-lite/

That was exactly where I found the answer on the web.
I bookmarked this FAQ as it looks very interesting.
The conclusion is: Dealing with malloc/free in C++ too much (or even at
all?!?) is not a good idea and should be avoided by using save
components from STL. Is that right?

Short answer: yes.

Thanks.

Jul 22 '05 #6

"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...
Hello,

Should I use malloc to reserve memory for my struct?


Never use malloc unless you know darn well that the struct consists of all
POD (Plain-Old-Data) members, *and will always consist of POD types*.. If
you need to dynamically create an object, use operator new. The reason is
that if you happen to change your struct to have, say a std::string, as a
member, your malloc() call will introduce undefined behavior. To guard
against this, you use the C++ way of creating an object, and that is by
invoking the proper constructor. Operator new calls this constructor when
you create the object dynamiclly, while malloc doesn't know squat about C++
objects or constructors. Your struct contains a "myObject" member. Is this
a POD type? If it isn't, your call to malloc cannot be used safely, period.

The same thing can be stated for many functions from the 'C'-library. For
example, using memcpy() and memset() on non-POD types leads to undefined
behavior, calling qsort() on non-POD types again, undefined behavior. I
once had to correct a problem where a programmer had a struct of all int
members and used memset() to initialize all members to 0. Then one day, a
std::string object was introduced. The call to memset() was never changed,
and the application that was working was all of a sudden crashing. Chaning
the memset() to proper initialization via constructor corrected the problem.

Basically, you should completely get out of defaulting to using 'C'
functions such as malloc(), since not only are they not necessary for your
case, it is invalid to use them in many circumstances.

Paul
Jul 22 '05 #7
Paul wrote:
"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...
Hello,

Should I use malloc to reserve memory for my struct?

Never use malloc unless you know darn well that the struct consists of all
POD (Plain-Old-Data) members, *and will always consist of POD types*.. If
you need to dynamically create an object, use operator new. The reason is
that if you happen to change your struct to have, say a std::string, as a
member, your malloc() call will introduce undefined behavior. To guard
against this, you use the C++ way of creating an object, and that is by
invoking the proper constructor. Operator new calls this constructor when
you create the object dynamiclly, while malloc doesn't know squat about C++
objects or constructors. Your struct contains a "myObject" member. Is this
a POD type? If it isn't, your call to malloc cannot be used safely, period.

The same thing can be stated for many functions from the 'C'-library. For
example, using memcpy() and memset() on non-POD types leads to undefined
behavior, calling qsort() on non-POD types again, undefined behavior. I
once had to correct a problem where a programmer had a struct of all int
members and used memset() to initialize all members to 0. Then one day, a
std::string object was introduced. The call to memset() was never changed,
and the application that was working was all of a sudden crashing. Chaning
the memset() to proper initialization via constructor corrected the problem.

Basically, you should completely get out of defaulting to using 'C'
functions such as malloc(), since not only are they not necessary for your
case, it is invalid to use them in many circumstances.

Paul


Thanks for your explanation of the problem, Paul.
So when I have non-POD types in my structure (let's take your example
with a struct full of ints and now with a std::string), is the situation
the following or am I taking something wrong(?): The std::string data is
allocated next to all the ints in memory and using a C function like
memset would set everything in the struct to 0, not only the character
date in std::string, but also other members???

My problem (until now) was, that I wasn't sure if it is good to use c++
features only, because it seemed some kind of inefficient and indirect
to me. But if programming pure c++ is commonly used in wild life, it
can't be that bad, so I'll try to get used to avoid mixing C and C++.

Thanks for your replies!

Christof Krueger

Jul 22 '05 #8
"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...
So when I have non-POD types in my structure (let's take your example
with a struct full of ints and now with a std::string), is the situation
the following or am I taking something wrong(?): The std::string data is
allocated next to all the ints in memory and using a C function like
memset would set everything in the struct to 0, not only the character
date in std::string, but also other members???
You've gotta get out of the 'C' mind Christof ;) In C, all your types are
POD, so the "rules" you are used to for POD should apply to non-POD right?
No. When your struct contains non-POD membera, the only way to initialize
the struct, and thereby the members, is by constructing it correctly. You
do not construct or initialize such objects using malloc and memset. That's
the bottom line.

What if the std::string needs to have specific members set correctly on
construction? How does malloc()-ing the memory for the struct set up these
members? It can't -- like I said, malloc() knows zip, zero, nada, about C++
objects. When you now use the improperly constructed object, what do you
think will happen if you use such an object? The only thing that sets up
the members correctly is the constructor call, and only operator new can do
this (if you create the object dynamically).

Now, what if the std::string is a reference-counted string? If you used
memcpy() on such an item, you will screw up the reference counting
mechanism. This is exactly the situation I mentioned in my previous post
where the program crashed.

My problem (until now) was, that I wasn't sure if it is good to use c++
features only, because it seemed some kind of inefficient and indirect
to me. But if programming pure c++ is commonly used in wild life, it
can't be that bad, so I'll try to get used to avoid mixing C and C++.


Another thing that 'C' programmers tend to think is that their C code is
faster than C++. Not only is this, for the most part, a bogus claim, it
also leads to coding improperly and incorrectly when you resort to coding in
the 'C'-style.

Paul
Jul 22 '05 #9
Paul wrote:
"Christof Krueger" <ne**@pop2wap.n et> wrote in message
news:br******** *****@news.t-online.com...

So when I have non-POD types in my structure (let's take your example
with a struct full of ints and now with a std::string), is the situation
the following or am I taking something wrong(?): The std::string data is
allocated next to all the ints in memory and using a C function like
memset would set everything in the struct to 0, not only the character
date in std::string, but also other members???

You've gotta get out of the 'C' mind Christof ;) In C, all your types are
POD, so the "rules" you are used to for POD should apply to non-POD right?
No. When your struct contains non-POD membera, the only way to initialize
the struct, and thereby the members, is by constructing it correctly. You
do not construct or initialize such objects using malloc and memset. That's
the bottom line.

Okay, just wanted to know "what if", to understand what happens behind
the scenes.
What if the std::string needs to have specific members set correctly on
construction? How does malloc()-ing the memory for the struct set up these
members? It can't -- like I said, malloc() knows zip, zero, nada, about C++
objects. When you now use the improperly constructed object, what do you
think will happen if you use such an object? The only thing that sets up
the members correctly is the constructor call, and only operator new can do
this (if you create the object dynamically).

Now, what if the std::string is a reference-counted string? If you used
memcpy() on such an item, you will screw up the reference counting
mechanism. This is exactly the situation I mentioned in my previous post
where the program crashed.

My problem (until now) was, that I wasn't sure if it is good to use c++
features only, because it seemed some kind of inefficient and indirect
to me. But if programming pure c++ is commonly used in wild life, it
can't be that bad, so I'll try to get used to avoid mixing C and C++.

Another thing that 'C' programmers tend to think is that their C code is
faster than C++. Not only is this, for the most part, a bogus claim, it
also leads to coding improperly and incorrectly when you resort to coding in
the 'C'-style.

I'me quite new to C and C++ programming both but I've seen more C code
than C++ code _before_ I started to actually program it myself. That is
why I still mix things up.
C code look intuitively faster, because its more complicated (not that
high level) and one think, that c++ programs have more overhead to
handle. But of course you can write a lot of *really* slow code in
low-level C :)
If you know some must-see links covering performance comparison between
C/C++ programs, please let me know.

Christof

Jul 22 '05 #10

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

Similar topics

46
4141
by: sbayeta | last post by:
Hi, I'd like to know who is responsible of memory recycling and defragmentation in a C/C++ program, assuming all the memory allocation/deallocation is done using malloc/free or new/delete. Thanks
36
7770
by: Bhalchandra Thatte | last post by:
I am allocating a block of memory using malloc. I want to use it to store a "header" structure followed by structs in my application. How to calculate the alignment without making any assumption about the most restrictive type on my machine? Thanks.
36
2267
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program code ... */
18
2122
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for last_values as well as assign the value of a pointer to the assigned space. Which I think I'm doing by using:
15
1845
by: sethukr | last post by:
Hi everybody, While running the following program in GCC, i'm very much screwed. main() { char *ptr1; char arr; int i; char *ptr2;
25
2248
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking. --- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct {
14
1930
by: Jef Driesen | last post by:
I'm writing a library (to communicate with a number of devices over a serial port) and have some questions about the design. I have now a header and source file like this: /* device.h */ typedef struct device device; int device_open (device **dev, const char *name); int device_close (device *dev); int device_read (device *dev, void *data, unsigned int size);
10
1900
by: somenath | last post by:
Hi All, I have one question regarding return value cast of malloc. I learned that we should not cast the return value of malloc because it is bug hider. But my question is as mentioned bellow . Lets say I have not included stdlib.h in my program still I am using malloc so compiler will throw warring because with out prototype
27
2768
by: matt | last post by:
Hello group, I'm trying to become familiar with the information hiding design rules, and I have a lot (3) of questions for all you experts. AFAIK, a generic module has 2 files: ================ module.h ================ #ifndef __MODULE_HDR_INCLUDED__
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9031
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...
0
8871
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...
0
7739
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6528
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.