linux-c-programming.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: James Colannino <james@colannino.org>
To: linux-c-programming@vger.kernel.org
Subject: Using realloc()
Date: Fri, 10 Jun 2005 23:07:33 -0700	[thread overview]
Message-ID: <42AA7FA5.4040806@colannino.org> (raw)

Hey everyone.  I have a question about realloc().  I was hoping to use
realloc() to allocate more memory to an already existing string, but the
problem was, I didn't know if the original information would stay intact
or not after running realloc().  I wrote the following program to test this:

#include <stdio.h>

int main() {

    char *string;
    size_t size = sizeof(char);

    string = (char *)malloc(size);
    string[0] = 'a';
    string[1] = '\0';

    printf ("Before realloc(): %p: %s\nsize: %d\n", string, string, size);

    size = size * 5;
    string = (char *)realloc(string, size);

    printf ("After realloc(): %p: %s\nsize: %d\n", string, string, size);

    return 0;
}

The string data stays the same after running realloc(), so at least in
this circumstance it worked like I had hoped.  However, when printing
the pointer to the screen, I saw that it didn't change, and I know that
sometimes realloc() needs to start at a new address in memory which
means the pointer changes, so my question is, will the original data
stay intact if this happens?

Thanks in advance :)

James

-- 
My blog: http://www.crazydrclaw.com/
My homepage: http://james.colannino.org/

"A well regulated militia being necessary to the security of a free
state, THE RIGHT of the people to keep and bear arms SHALL NOT BE
INFRINGED." --United States Constitution, Second Ammendment


             reply	other threads:[~2005-06-11  6:07 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2005-06-11  6:07 James Colannino [this message]
2005-06-11  8:08 ` Using realloc() Steve Graegert

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=42AA7FA5.4040806@colannino.org \
    --to=james@colannino.org \
    --cc=linux-c-programming@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).