Archived

This topic is now archived and is closed to further replies.

bezier128

C /C++ memory allocation question

Recommended Posts

I read somewhere in my compiler''s documentation that the C function realloc() always attempts to use the same memory location. If it cannot use the same location, when it allocates a new piece of memory, is the content of the old location copied into the new location? Example: char *charptr = (char*)malloc(2);// I create a pointer and // allocate some ram charptr[0] = ''A''; charptr[1] = ''B''; charptr = realloc(charptr, 4); //Then I reallocate with 4 bytes Will the first 2 bytes located at charptr be the same if realloc() has to use a different memory location? Also, does the C++ operator "new" attempt to use the same memory location? Bezier128

Share this post


Link to post
Share on other sites
I read somewhere in my compiler''s documentation that the C function realloc() always attempts to use the same memory location.

That''s not guaranteed. It is implementation dependent behaviour. Other compilers may do it differently.

If it cannot use the same location, when it allocates a new piece of memory, is the content of the old location copied into the new location?

Yes.

Will the first 2 bytes located at charptr be the same if
realloc() has to use a different memory location?


Not guaranteed. You should never count on it being the case.

Also, does the C++ operator "new" attempt to use the same memory location?

No. new always allocate a new block to create an object in unless you are using a placement new call (beyond the scope of this question). It implements none of the semantics of realloc.

C/C++ memory allocation question

C and C++ have incompatible memory allocation mechanisms.

Keep in mind that memory allocated be freed by matching calls - malloc/realloc/calloc with free - new by delete, new [] by delete[], and so on for platform-specific allocation routines (shmalloc ...)


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites