Solved

convert C->C++ : malloc

Posted on 2004-09-25
7
233 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
Comment Utility
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
Comment Utility
>>> 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
Comment Utility
>>... but you shouldn't.

Why not for POD? ANd how have I been wrong so that code needed some correction?
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 15

Expert Comment

by:efn
Comment Utility
>> 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
Comment Utility
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
Comment Utility
>>>> 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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

771 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

12 Experts available now in Live!

Get 1:1 Help Now