[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    Re: realloc question
From:       <uwe () uwix ! alt ! na>
Date:       1998-12-30 21:42:37
[Download RAW message or body]

On Wed, 30 Dec 1998, Szymon Stefanek wrote:

> Hi all!
> 
> I think that this is a good place to ask :)
> 
> char * buffer_ptr = malloc(10);
> memmove(buffer_ptr,"1234567890",10);

You are aware of the fact that buffer_ptr doesn't point to a real string
(not /0 terminated), are you?

> char * pointer_to_five = buffer_ptr+4;
> buffer_ptr = realloc(20);
> 
> now buffer_ptr points to the beginning of a 20 bytes buffer like this:
> "1234567890**********"
> 
> but where points 'pointer_to_five' ? :)

pointer_to_five _might_ point to "567890**********". It might.

If you increase a buffer by using realloc() two different scenarios are
possible (besides 'out of memory' of course):

1.
There is sufficient memory available directly behind the old buffer. In
this case realloc() indeed extends the old buffer and pointer_to_five
is valid.

2.
There isn't sufficient memory available directly behind the old buffer.
In this case realloc() allocates a completely new buffer of the new size
somewhere else, copies the content of the old buffer to the new one, and
deallocates the old buffer. Your pointer_to_five points to a portion of
memory which is not in use.  :-(

Uwe

-------------------------------------------------------------------------
Uwe Thiem                                        Tel: +264 - 061 - 244511
P.O.Box 30955                                    Fax: +264 - 061 - 244511
Windhoek                                         Email:   uwe@uwix.alt.na
Republic of Namibia                                           uwe@kde.org
                                                       http://www.kde.org
                  **********************************
         You can still escape from the GATES of hell: Use KDE!
-------------------------------------------------------------------------

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic