hello,
i am trying to store some values in an array dynamically.
doing this as i dont want to over allocate memory to my array. so the code goes as follows::

#include<stdio.h>
#include<stdlib.h>
int *p;
main()
{
int i;
for(i=1;i<6;i++)
{	p= (int *)malloc(sizeof(int));
	*p++ = i*i;
}
printf("\n %d %d",*p,*(p+1));
}

but in the output am getting all 0's stored in *p...
can someone help me?

Recommended Answers

All 4 Replies

You need to use the realloc() function to allocate additional storage and copy the contents from the previous allocation. You are calling malloc() in your loop which is clobbering memory.

You call malloc once and then call realloc whenever you need to allocate additional memory and retain the contents already allocated.

You should also be checking that calls to malloc (and realloc) are successful. If memory allocations are successful you should also be calling free to return it back to the OS when you're done with it.

You need to use the realloc() function to allocate additional storage and copy the contents from the previous allocation. You are calling malloc() in your loop which is clobbering memory.

You call malloc once and then call realloc whenever you need to allocate additional memory and retain the contents already allocated.

You should also be checking that calls to malloc (and realloc) are successful. If memory allocations are successful you should also be calling free to return it back to the OS when you're done with it.

thanks a lot. it works now.
a follow-up doubt :- once i am done with the program, say if i do not return it back to the OS, will it cause a problem the next time i compile and re-run it??
would that memory allocated still be used by the previous run?

thanks a lot. it works now.
a follow-up doubt :- once i am done with the program, say if i do not return it back to the OS, will it cause a problem the next time i compile and re-run it??
would that memory allocated still be used by the previous run?

It shouldn't cause any problems. There is probably no need to free memory blocks at the end of a program - all memory should be returned to the system once the program terminates - I suppose it's just a habit of mine that I free any memory that I allocate in a program regardless.

oh okay!
thanks a lot for your help!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.