Re: realloc()
- From: websnarf@xxxxxxxxx
- Date: 4 Sep 2006 15:50:18 -0700
Andrew Clark wrote:
websnarf@xxxxxxxxx wrote in
Do a "structured walk through". Here you will notice that you are
incrementing count to one more than the value used to allocate the
size above.
That's intended. See below.
But you are missing the point.
if (p)
{
p [count - 2] = x;
p [count - 1] = 0;
Meaning that count-1 actually is the offset which is one past the end
of the array which *arr is pointing at. I.e., if you just move the
count = (p ? count + 1 : 1) line down to below this if() clause I
think you will be ok.
}
return rc;
}
BTW, how are you planning on accessing the items of this array? You
don't know how long it is except for within the scope of the push()
call. Are you just going to assume that 0 is a sufficient of array
marker? I.e., are you basically disallowing 0's in your array except
as an end marker?
In the context of the ints in the array, 0 is not allowed, so it can
serve my purpose of an end marker. That's why I allocate 1 more than I
actually use - to store that 0.
Change your code to the following:
int push (int **arr, int x) {
int rc, *p;
static int count = 1 + 1;
*arr = realloc (*arr, sizeof x * count); /* segfault here */
p = *arr;
rc = (p ? 1 : 0);
if (p)
{
p [count - 2] = x;
p [count - 1] = 0; /* <==== */
}
count = (p ? count + 1 : 1); /* this line has been moved down */
return rc;
}
And your segfault will magically disappear. Now, walk through the code
by hand step by step and try to figure out what happens at the /* <====
*/ line before and after the change.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- Follow-Ups:
- Re: realloc()
- From: Andrew Clark
- Re: realloc()
- References:
- realloc()
- From: Andrew Clark
- Re: realloc()
- From: websnarf
- Re: realloc()
- From: Andrew Clark
- realloc()
- Prev by Date: Re: Global variables in Shared Libraries in Linux
- Next by Date: Re: efficiency match.
- Previous by thread: Re: realloc()
- Next by thread: Re: realloc()
- Index(es):
Relevant Pages
|
Loading