F
Francois Grieu
Can a pointer passed to sucessful realloc be used later in pointer
arithmetic? This would sometime help fix pointers that pointed into
the original block, so that they point properly in the new one.
In other words, is the following program conformant?
#include <stdlib.h>
int main(void)
{
char *p,*q,*r;
// allocate a block of 40 chars
if ((p = malloc(40))==NULL)
return EXIT_FAILURE;
// set q to point 20 chars into the block
q = p+20;
// poke an 'x' at q
*q = 'x';
// extend the block to 80 chars
if ((p = realloc((r=p),80))==NULL)
{
free(r);
return EXIT_FAILURE;
}
// the realloc() may have made q invalid, fix it
q = (q-r)+p;
// display the 'x'
printf("%c\n",*q);
free(p);
return EXIT_SUCCESS;
}
The statement q = (q-r)+p; is questionable since q and r are
pointers into a block that was passed to a sucessful realloc. I guess
q += p-r; is even more likely to turn wrong.
TIA for your comments, preferably with reference to the text of some C
standard.
Francois Grieu
arithmetic? This would sometime help fix pointers that pointed into
the original block, so that they point properly in the new one.
In other words, is the following program conformant?
#include <stdlib.h>
int main(void)
{
char *p,*q,*r;
// allocate a block of 40 chars
if ((p = malloc(40))==NULL)
return EXIT_FAILURE;
// set q to point 20 chars into the block
q = p+20;
// poke an 'x' at q
*q = 'x';
// extend the block to 80 chars
if ((p = realloc((r=p),80))==NULL)
{
free(r);
return EXIT_FAILURE;
}
// the realloc() may have made q invalid, fix it
q = (q-r)+p;
// display the 'x'
printf("%c\n",*q);
free(p);
return EXIT_SUCCESS;
}
The statement q = (q-r)+p; is questionable since q and r are
pointers into a block that was passed to a sucessful realloc. I guess
q += p-r; is even more likely to turn wrong.
TIA for your comments, preferably with reference to the text of some C
standard.
Francois Grieu