Allocate more memory

S

shilpi

Hi,
I am trying to allocate mroe memory if the following condition is true.
But I get Invalid pointer write memory error when running this code
through purifier.It is not freeing up oldlevels
Any help appreciated.

if(numLevels >= numAlloc) {
//printf("Allocate more memory\n");
char **oldLevels = levels;
long *oldOrder = order;
numAlloc *= 10;
levels = (char **) calloc(numAlloc, sizeof(char *));
order = (long *) calloc(numAlloc, sizeof(long));
for(i = 0; i < numLevels; i++) {
levels = oldLevels;
order = oldOrder;
}
free(oldLevels);
free(oldOrder);
}
 
J

Josh Mcfarlane

shilpi said:
Hi,
I am trying to allocate mroe memory if the following condition is true.
But I get Invalid pointer write memory error when running this code
through purifier.It is not freeing up oldlevels
Any help appreciated.

if(numLevels >= numAlloc) {
//printf("Allocate more memory\n");
char **oldLevels = levels;
long *oldOrder = order;
numAlloc *= 10;
levels = (char **) calloc(numAlloc, sizeof(char *));
order = (long *) calloc(numAlloc, sizeof(long));
for(i = 0; i < numLevels; i++) {
levels = oldLevels;
order = oldOrder;
}
free(oldLevels);
free(oldOrder);
}

Please don't double post on the list. But the error you are having
might be due to the fact that if numLevels >= (numAlloc*10), you will
still not have enough allocated memory.
 
R

ravinderthakur

hi shilpi,

there is a function in the c library that does exactly the same thing
viz realloc
u can code in the following way...


if(numLevels >= numAlloc) {
//printf("Allocate more memory\n");
numAlloc *= 10;
levels = (char **)realloc(levels, numAlloc *
sizeof(char *));
order = (long *) realloc(order , numAlloc *
sizeof(long));
}

in case of any clarification,plz see the documentation of realloc.

thanks
rt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top