Re: why does this happen?
From: Andrew Koenig (ark_at_acm.org)
Date: 03/29/05
- Next message: Andrew Koenig: "Re: why does this happen?"
- Previous message: Materialised: "Would this be safe?"
- In reply to: Billy Patton: "why does this happen?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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?
- Next message: Andrew Koenig: "Re: why does this happen?"
- Previous message: Materialised: "Would this be safe?"
- In reply to: Billy Patton: "why does this happen?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|