pointers & order of execution

Tapani Tarvainen tarvaine at tukki.jyu.fi
Sat Jul 22 23:47:51 AEST 1989


Consider the following code fragment:

	b = (char *) malloc(n);
	c = b + x;
...
	t = b;
	b = (char *) realloc(b, m);
/*1*/	i = b - t;
	c += i;

The idea is that c keeps pointing to the same thing.
Is this guaranteed to work?  I think not:
pointer subtraction assumes the pointers point to
the same structure, which b and t don't (unless pANS
says something about realloc in this context?).
And indeed, it may fail with Turbo C and probably any 80x86 C with
large data models.  (The problem came up when porting Gnu grep to
ms-dos.  See article <920 at tukki.jyu.fi> in gnu.utils.bug for details.)


Then how about this:

/*2*/	c = b + (c - t);

Is this guaranteed to work, or is the compiler free to rearrange it as

	c = (b - t) + c;

even though b - t is illegal (and fails)?

I know it can be done safely like this:

	i = c - t;
	c = b + i;

which is what I did, but I'd like to know what pANS says about /*2*/.

-- 
Tapani Tarvainen                 BitNet:    tarvainen at finjyu
Internet:  tarvainen at jylk.jyu.fi  -- OR --  tarvaine at tukki.jyu.fi



More information about the Comp.std.c mailing list