Jack said:
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().
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