Re: realloc()



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/

.



Relevant Pages

  • Re: show disassembly
    ... - when I pass an array to a function it looks like the function ... int * mySortedArray; ... The memory allocated for `mySortedArray' is leaked. ... You don't need to allocate new array. ...
    (microsoft.public.vc.language)
  • Re: When/why to use size_t
    ... Someone might want to allocate more memory than will fit in an int. ... Any array could have been allocated with malloc. ... chance of the assets triggering. ...
    (comp.lang.c)
  • Re: pointer/allocation question
    ... > allocated array of 5000 bytes. ... > void allocate(int *array, int length) ... the value of the pointer list in main. ... Finally, if you fix the program it will allocate 5000 bytes of memory, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: MATRIXES - Dinamic Memory
    ... matrix is a pointer to int. ... allocate an array of pointers *and* allocate each of the rows. ...
    (comp.lang.c)
  • [patch 04/30] Fix sys_move_pages when a NULL node list is passed.
    ... sys_move_pagesuses vmallocto allocate an array of structures ... depends on a marker in the node field of the structure to decide how large ... the array is and this marker is correctly inserted into the last element ... vmalloc() doesn't zero the memory it allocates ...
    (Linux-Kernel)

Loading