Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

SteveBe

Memory allocation

This topic is 5941 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 [i] subscript the next time through the loop.

Share this post


Link to post
Share on other sites
Advertisement
Test the subscript before assigning values to the memory chunk. If subscript % 20 == 0 then allocate more memory and continue forward.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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;
}
}
}

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!