Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sites with pointers and realloc

Status
Not open for further replies.

ggggg

Programmer
Apr 18, 2000
5
US
If you know any site about pointers and realloc
tell me!
 
What are you confused on? Maybe we can help you here :)

Briefly (well, I'll try to be brief):

1)
Only use realloc() on a pointer that points to memory that has been allocated previously by malloc(), calloc() or realloc().

2)
/Always/ use a temporary pointer to store the return value from realloc():

#define CHUNK_SIZE 1024 /* just an arbitrary number */

/* Use this to keep track of how many bytes you've
* allocated for data
*/
size_t bytesAllocated=CHUNK_SIZE;
char *data=malloc(CHUNK_SIZE);
char *tmp;

/* ... */

/* sometime later ... */
tmp=realloc(data,bytesAllocated+CHUNK_SIZE);
bytesAllocated+=CHUNK_SIZE;

if (NULL!=tmp) {
data=tmp;
} else {
fprintf(stderr,"realloc() failed!\n");
free(data);
}

It is important to do it like this because if realloc() were to fail and you were to assign data the return value rather than use the temporary pointer, data would be assigned NULL and the memory that data previously pointed to would now be inaccessible which makes it impossible to free() it which causes a memory leak.

3)
realloc() calls are expensive in terms of time, so don't use them with great frequency. In other words, if you have a buffer that may need to grow over time, choose a chunk size that's big enough such that the number of calls to realloc() is kept at a minimum. There's a balance here between abusing memory and abusing speed, which obviously requires different decisions depending on the problem.

I don't know of any sites offhand that address realloc() specifically, but this might help:


If you have specific questions, feel free to post here.

Hope this helped.

Russ
bobbitts@hotmail.com
 
Thanks you really helped!:)
But i want to ask you something else:Should we use a temp pointer for char **data?
 
What for?
char **ppcArray;
if you are trying to realloc this array of string you will realloc only the array of pointers not your strings and all values of pointers will stay valid.
So what are you trying to put in tmp pointer?
In other case if you have
char (*pacArray)[100];
You will realoc all data by one call to realloc.
 
Who are you responding to Lim? And...um...what are you saying?

Thrillos, you should always use a temporary pointer to store the result of realloc(), as explained above.

Could you explain more what you're trying to do?



Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top