Re: why does this happen?

From: Andrew Koenig (ark_at_acm.org)
Date: 03/29/05


Date: Tue, 29 Mar 2005 20:49:28 GMT


"Billy Patton" <bpatton@ti.com> wrote in message
news:Pine.LNX.4.61.0503291256490.596@holster07.dal.design.ti.com...

> #include <string>
>
> using namespace std;
>
> typedef struct
> {
> string path;
> int val;
> } test_t;
> typedef test_t *test_p;
>
> test_p tp_malloc(void)
> {
> test_p tp = (test_p) malloc(sizeof(test_t));
> return tp;
> }

Don't do this!

In general, you should avoid using malloc in C++ programs.

More specifically, you should never use malloc when you are dealing with
types that have constructors or destructors.

So in this case, you should write

    test_p tp_malloc()
    {
        test_p tp = new test_t;
        return tp;
    }

Unless you use "new" to allocate objects of type test_t, the objects will
not be constructed properly, and there is no saying what will happen.

> int main(void)
> {
> test_p tp = tp_malloc();
> string s = "abcd";
> tp->path = s;

Unless you use new rather than malloc, there is absolutely no guarantee that
this will work.

> return 0;
> }
>
> test_t is a c structure but sontaing the STL string.
> In may data I cannot use new yet because of all these structures.
> So malloc is creating the memory but it does not initialize the string
> path because it was done by malloc instead of new.
> I know if I changed path to string* path, then in the tp_malloc do a tp =
> new string, ith should probably work ok. But I would kile to avoid this
> to have the destructors work properly.

What do you mean?



Relevant Pages

  • why does this happen?
    ... typedef struct ... test_t is a c structure but sontaing the STL string. ... So malloc is creating the memory but it does not initialize the string path ...
    (alt.comp.lang.learn.c-cpp)
  • Re: why does this happen?
    ... > typedef struct ... > So malloc is creating the memory but it does not initialize the string path ... > because it was done by malloc instead of new. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: how to store list of varying types
    ... When there's a variable-length string, ... typedef struct { ... pointer null, and the second one the CString object. ... then have to finish constructing the packet by copying the two data objects ...
    (microsoft.public.vc.mfc)
  • Re: MVC in C++
    ... Things are now flowing more along the classic MVC lines. ... > struct Observable ... > string version; ... In that case the Controller would trigger a model update *and it* could ...
    (comp.object)
  • Re: Linked List & Dynamic Memory Allocation
    ... for every call to malloc but when I do that inside the for loop I end ... You attach a string to the ... you can find your lunch is to start at the tag labeled "lunch" and follow it to the box on ... Suppose I have 1000 cubic feet of "memory". ...
    (microsoft.public.vc.mfc)