• Advertisement
Sign in to follow this  

how to malloc memory properly?

This topic is 2387 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

I have a problem with malloc function.
I am using mallog in the manner:
[code]
TMyClass *ClInstancePtr;

CInstancePtr=(TMyClass*) malloc(sizeof(TMyClass)*NumOfElements);
[/code]
And it doesn't work properly. It behaves just lke I hadn't allocated anything.
F ex.:
[code]
ClInstance[2]=some values;
cout<<ClInstance<<endl;
output - some random data.
[/code]
What am I doing wrong?

Thanks in advance for any help.
Regards,
Misery.

PS.: When I use new[ ]/delete [ ] it works fine.

Share this post


Link to post
Share on other sites
Advertisement
Using [b]malloc[/b] doesn't construct any object in the array, it only allocates the requested memory.

Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?

Share this post


Link to post
Share on other sites
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]

Use stl containers instead, it will save you a lot of bother. However, for the sake of explanation... you'll have to copy the data over anyway as malloc will allocate memory at a DIFFERENT address to the one you got when you first called malloc, thus you will lose the data. Not only that, but it will be leaked memory as you didn't free it before reallocating new memory. Anyway, use the new and delete operators as they are the "proper way of doing things", and for good reason. To allocate and delete arrays, you use new[] and delete[] operators respectively. If you wish to resize a dynamically created array, you would allocate a temporary dynamic array of existing size and then copy the contents of your existing array across. Then you would delete the contents of your existing array and reallocate a new array of the desired size, before transferring the contents of your temporary array across. Finally, delete you would the temporary array.

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]

why not just use a vector or list ? (std::vector or std::list)

anyway as vdaras said malloc doesn't construct the object (the constructor is never called) it only allocates memory for it. (malloc is the C way of allocating memory, C doesn't support classes so trying to use a memory block allocator to create class instances will result in some major headaches)

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309620650' post='4830366']
Does something like [b]vector<bool>[/b] tell You guys something?:cool:

[/quote]

I'm not following. You can have containers of objects, no problem.

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309620650' post='4830366']
Why not stl?
Does something like [b]vector<bool>[/b] tell You guys something?:cool:
Thats why not stl.
[/quote]


Don't use STL because it allows you to create a resizeable bool array?

Share this post


Link to post
Share on other sites
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?

Share this post


Link to post
Share on other sites
[quote name='King Joffrey' timestamp='1309621370' post='4830369']
[quote name='Misery' timestamp='1309620650' post='4830366']
Does something like [b]vector<bool>[/b] tell You guys something?:cool:

[/quote]

I'm not following. You can have containers of objects, no problem.
[/quote]


Blind guess: He's probably referring to the overhead. Well, you also have the same with an array of bools. If you want to use only a single bit for each bool you need to use bitmasks on top of that. Still until now, there wasn't a single reason not to consider STL containers.

Share this post


Link to post
Share on other sites
[quote name='Michael N.' timestamp='1309621586' post='4830372']
[quote name='King Joffrey' timestamp='1309621370' post='4830369']
[quote name='Misery' timestamp='1309620650' post='4830366']
Does something like [b]vector<bool>[/b] tell You guys something?:cool:

[/quote]

I'm not following. You can have containers of objects, no problem.
[/quote]


Blind guess: He's probably referring to the overhead. Well, you also have the same with an array of bools. If you want to use only a single bit for each bool you need to use bitmasks on top of that. Still until now, there wasn't a single reason not to consider STL containers.
[/quote]
[i]std::vector<bool>[/i] is a specialization that stores bools tightly packed. This is mandated by the specification.

Share this post


Link to post
Share on other sites
I need resizable bool array with tightly packed data. i mean one bit = one bool value.
Second thing is that I will use millions of instances of this class. And vector<bool>
requires (with zero entries) 20 bytes of memory. At start. Thats too much.
Therefore I have decided to create a class that has ability to resize, contains chars, and has ability to access every bit in char.
The only last problem is how to resize this fast.

Why did You guys vote down?

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]Then the problem is that you need to stop wanting to do that. Get out of this mindset that copying is slow - It isn't. Heck [url="http://lwn.net/Articles/255364/"]here[/url]'s a good read on how they modified a matrix multiply routine to copy the matrix internally leading to a more than four times speedup.


You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.

Share this post


Link to post
Share on other sites
[quote name='iMalc' timestamp='1309639192' post='4830459']
You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.
[/quote]
Well, although Misery was beginner, this is not beginners forum...

I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:


Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1309629739' post='4830410']
Assuming two pointers and an integer, that adds up to 20 bytes (assuming a 64 bit system with 64 bit pointers and 32 bit integers).
[/quote]
To be fair, MSVC 2010 has a 20 byte std::vector<bool> even in 32 bit release builds. Its std::vector<bool> is implement in terms of std::vector<unsigned int>; it's the size of std::vector<unsigned int> plus its own data.

Share this post


Link to post
Share on other sites
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]

How to do it properly? I will use memory pools anyway, but I need to finish that class I have begun.

And I'm not really a beginner, however I am not educated programmer, but fluid mechanics engineer, so many things for me are unclear.
I'm just an user of programming.

Thanks for any help.

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1309621495' post='4830371']
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?
[/quote]

vector <bool> has not only strange non-stl semantics. It also forces compiler to optimise code inproperly. If many clever ppl say: never use vector<bool> i do not use it.
And the other thing is that vectors are quite big 20 bytes for an empty vector. One more thing is that vectors reserve much more memory than needed. I know that one can use v.reserve()
but after I exceed reserved memory it will reserve again twice more than needed and so on.
In fact I need a bit array. My basic class is byte that allows me to access every bit.

Share this post


Link to post
Share on other sites
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
[quote name='iMalc' timestamp='1309639192' post='4830459']
You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.
[/quote]
Well, although Misery was beginner, this is not beginners forum...

I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]Then you [i]appear[/i] to be an exception to the rule.

Of course using realloc etc was at best unnecessary, and at worst you just haven't seen the issues yet and they'll still get you one day.

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309689528' post='4830574']
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]

How to do it properly? I will use memory pools anyway, but I need to finish that class I have begun.

And I'm not really a beginner, however I am not educated programmer, but fluid mechanics engineer, so many things for me are unclear.
I'm just an user of programming.
[/quote]
[code]MyType *newptr = (MyType *) realloc (oldptr, newsize * sizeof (MyType));
for (size_t i = oldsize; i < newsize; i++) {
// Initialize your new data here
}[/code]
[list][*]Do not try it with non-POD types! Although there is placement new, things get ugly fast.[*]Do not forget, that the block address may change - thus you should NOT keep extra pointers to it.[*]Do not forget, that your old memory block may be freed and completely new one allocated. Thus you cannot keep pointers to individual objects.[*]Your old objects (datablocks) will be copied bit-by-bit. If this is not the intended behaviour, do not use it.[*]Your new objects (datablocks) will be uninitialized - i.e. filled with arbitrary garbage.[*]If new memory block is allocated, neither destructors nor copy contructors are called[*]It is better to avoid MyType constructors altogether. Then you cannot expect it to be called (it won't).[/list]
In general, there should be very good reasons to use malloc/realloc/free in C++ code. One possible cause is to reduce unnecessary pointer dereferencing - something like:

[code]struct VectorPath {
unsigned int size;
unsigned int nelements;
Rect bbox;
float coordinates[2];
};[/code]

In this example you can construct paths of arbitrary length by allocating more memory than the size of given struct and then access coordinates >= 2. I think this may be violating C/C++ standard, but I do not think there is or will be any compiler that does not support it. But in any case such constructs require good and clean encapsulation - or they'll bite you.

My suggestion is - use new/delete and copy manually, or use vectors. Encapsulate the required behaviour into clean API and get your program working. Then you can experiment with more esoteric things ;-)

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309689870' post='4830576']
[quote name='Hodgman' timestamp='1309621495' post='4830371']
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?
[/quote]

vector <bool> has not only strange non-stl semantics. It also forces compiler to optimise code inproperly. If many clever ppl say: never use vector<bool> i do not use it.
And the other thing is that vectors are quite big 20 bytes for an empty vector. One more thing is that vectors reserve much more memory than needed. I know that one can use v.reserve()
but after I exceed reserved memory it will reserve again twice more than needed and so on.
In fact I need a bit array. My basic class is byte that allows me to access every bit.
[/quote]


Why not override the allocator?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement