Jack schrieb:
Eric Sosman wrote:Jack wrote On 06/02/06 12:54,:
In the following code:
char *p;
while(1){
p = malloc(10*sizeof(*p));
//Do something with p
}
The while( ) loop keeps allocate memory to p. What will happen?
Each iteration of the loop will call malloc() and
request another ten bytes. Unless the "do something"
code free()s some of the allocated memory, malloc()
will eventually exhaust all the available memory and
return NULL to indicate that it couldn't honor the
request.
Assume that 5 blocks of ten bytes memory are allocated, which one does
p points to?
the last one?
Please be precise in your questions -- I am not sure whether you
are asking for the value of p or the relative position of allocated
storage...
p at "// Do something ..." obviously either is a null pointer
(perfectly possible) or points to at least 10 bytes of
allocated storage.
As long as p does not become a null pointer, p points to the storage
returned by the latest call to malloc().
Should I do as below?
char *p;
while(1){
p = malloc(10*sizeof(*p));
//Do something with p
free(p);
}
That is one thing you could do. Another would be
p = malloc(10 * sizeof *p;
if (p == NULL) ...
while (1) {
//Do something with p
}
free (p); // assume a `break'
Still another might be to put the p values into a data
structure of some kind -- linked list, tree, whatever --
that will "remember" the values so you can access the
allocated memory later.
If each time I have to allocate a different size of memory to p, such
as:
p = malloc(N * sizeof(*p)); //N is a variable
then I have to put the malloc into the while loop, right?
Not necessarily.
It may suffice to know the value range N can have during a
run of the programme and allocate sufficiently much storage
before the loop.
Or have an array of the respective size.
Another thing would be to have
size_t size = 0;
char *p = NULL;
p = malloc(INIT_SIZE * sizeof *p);
if (p == NULL) {
/* Your error handling here */
}
size = INIT_SIZE;
while (1) {
....
if (N > size) {
char *temp = realloc(p, N);
if (temp == NULL) {
/* Your error handling here; p is still valid */
}
p = temp;
size = N;
}
....
free(p);
If you explain what exactly you have in mind, we may be able
to help you better.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.