Advertisement

Memory allocation

Started by September 13, 2002 04:12 AM
4 comments, last by SteveBe 22 years, 3 months ago
int *p; p = (int *)malloc (20 * sizeof (int)); This is at the start of a loop in my program. Each time through the loop a number is being added to p. When I get to the bottom of the loop, how do I check to see if p is "full" and then if it is, allocate a further 20 integers to p, all the while preserving the first twenty that I have allocated so I can continue using p with an incremented subscript the next time through the loop. </i>
Test the subscript before assigning values to the memory chunk. If subscript % 20 == 0 then allocate more memory and continue forward.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Advertisement
but if I do another p=(int *)malloc(20 * sizeof (int)) will it not just overwrite the contents of the first twenty numbers stored in p? I want to make sure that it just tacks it onto the end of the first 20, all the while keeping the numbers stored in p0-p19.
Yes - sorry. Use realloc to expand the chunk. It''s supposed to preserve the previous memory. Also do you have an estimate of what the upper bounds might be? Consider breaking off a bigger chunk to start with so that it''s less likely that you''ll need to realloc as realloc can be slow. No use pinching on bytes when you have megabytes at your disposal. Break off a kb or three if you need it.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
You might want to look up realloc, or vector. I recommend vector
int* p = 0;

for (int index = 0; index < someNumber; index++)
{
if (p == 0)
{
p = (int*)malloc (20 * sizeof(int));
if (p == 0)
{
// malloc failed, handle error
}
}
else
{
int* temp = (int*)realloc ((void*)p, ((index + 1) * 20) * sizeof (int));
if (temp == 0)
{
// realloc failed, but p is still valid
}
else
{
p = temp;
}
}
}

This topic is closed to new replies.

Advertisement