Solved

convert C->C++ : malloc

Posted on 2004-09-25
7
235 Views
Last Modified: 2012-05-05
Hi, I have a question:
I want to know how malloc should be "converted to" C++ in the following case:

°°°°°°°header°°°°°°
typedef struct A_STRING
{
      int16*                  buffer;
      unsigned long      length;
}_STRING, *P_STRING;
°°°°°°°°°°°°°°°°°°°

°°°°°°°cpp°°°°°°°°°
P_STRING pStr = new _STRING;
int a ;//used to find how much elements there are in
pStr->buffer = (int16 *) malloc(a);
°°°°°°°°°°°°°°°°°°°

DEEGBAL

0
Comment
Question by:DEEGBAL
7 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 12150646
You still can use 'malloc()'  in C++, but if you want, you can switch to 'new' here also:

P_STRING pStr = new _STRING;
int a ;//used to find how much elements there are in
pStr->buffer = new int16 [ a];
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 75 total points
ID: 12150761
>>> You still can use 'malloc()'  in C++

... but you shouldn't.


class String
{
private:
     int16*               buffer;
     unsigned long    length;
public:
     String() : buffer(NULL), length(0) { }
     String(int a) : buffer(new int16[a]), length(a) { }
    ~String() { delete [] buffer; }
};

typedef String* StringPtr;

void main()
{
        int a = getAFromeSomeWhere();
       StringPtr pStr = new String(a);
}

Regards, Alex
0
 
LVL 86

Expert Comment

by:jkr
ID: 12150800
>>... but you shouldn't.

Why not for POD? ANd how have I been wrong so that code needed some correction?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 15

Expert Comment

by:efn
ID: 12152564
>> Why not for POD?

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3

An additional consideration is that avoiding malloc will make it easier for future young punk upstart whippersnappers who didn't learn C before C++ to maintain your code.  More generally, the fewer different ways you do things, the simpler, the better.

On the other hand, if you expect your code to be maintained in the future by crusty old C programmers, maybe you should avoid the new operator.

--efn
0
 
LVL 23

Expert Comment

by:Mysidia
ID: 12153312
Why you shouldn't mix them is because it is error prone...

For example, the following snippets both have a serious error:

char *x = (char *)malloc(15);
delete x;  /* Can't mix  malloc and delete : undefined behavior */

char * y = new char[15];
free(y); /* Can't mix new and free : undefined behavior */


This is most important when writing functions whose result is dynamically
allocated, and the caller needs to manage the memory.

There is a great risk that the programmer will mistakenly use the wrong convention
for releasing the memory.

To retain your development team's sanity, it is best to choose one of the conventions
and stick to it:  Either always use 'new' or always use 'malloc()', but don't mix them if
it can be avoided.

(One case where it cannot be avoided is if you need to resize the memory area...
there isn't an equivalent to C++'s realloc() provided for memory allocated with the
new[] operator)

new is often best to use, because that is what most C++ programmers and the C++ libraries
are using

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12154299
>>>> ANd how have I been wrong so that code needed some correction?

jkr, what did you make come to the assumption that my code was a correction of your's. If i make corrections i post the wrong code and the corrected one. I thought there is a common accordance between C++ programmers not to mix C++ and C style, especially if there isn't any need for that. As your first statement about malloc and C++ was technically correct, but in contradiction to that or at least misunderstandable, i made an objection and posted C++ code to demonstrate the C++ way how to solve these kind of tasks.

BTW, your code wasn't quite correct as the variable "a" had not been initialized and the questioner made "malloc(a)"  while your code made "new int16[a]", what most likely is better but not the same.

Regards, Alex

0
 

Author Comment

by:DEEGBAL
ID: 12154327
Hi,
first of all, thanks all for your help and your comments.
Since I copied-and-pasted the code of itsmeandnobodyelse, and everything directly worked fine, I'll give him the points.

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
MSVCR80.dll crash 2 134
Modify static variables within a class in VC++ 3 95
computer science syllabus 3 70
Arduino EDI - Programming language 3 80
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now