Pointing outside the heap

J

Jon Harrop

Is the following code invalid C:

char *a = malloc(1);
a--;
a[1] = 3;

because there is an intermediate pointer that points outside the array?
 
H

Harald van =?UTF-8?B?RMSzaw==?=

Jon said:
Is the following code invalid C:

char *a = malloc(1);
a--;
a[1] = 3;

because there is an intermediate pointer that points outside the array?

Correct. There is an exception that allows pointers to point just after the
end of an array, but there is no similar exception for a pointer to point
just before the start of an array.
 
B

Ben Pfaff

Jon Harrop said:
Is the following code invalid C:

char *a = malloc(1);
a--;

The above two lines by themselves invoke undefined behavior.
a[1] = 3;

because there is an intermediate pointer that points outside the array?

The three lines of code as a group also invoke undefined
behavior, yes, and that's the reason: pointer arithmetic is only
allowed within an array or one-past-the-end of an array.
 
C

Chris Dollin

Jon said:
Is the following code invalid C:

char *a = malloc(1);
a--;
a[1] = 3;

Yes; it's invalid in the sense that the effect of
executing it is left completely open ("undefined")
by the Standard.

Implementations may do what they will with it, and may
assume that the programmer hasn't been wicked enough to
do things like it.
because there is an intermediate pointer that points
outside the array?

Because it attempts to compute a pointer that lies outside
an allocated object. (There's no such "intermediate pointer",
because trying to compute it leaves you in limbo.)
 
M

Malcolm McLean

Jon Harrop said:
Is the following code invalid C:

char *a = malloc(1);
a--;
a[1] = 3;

because there is an intermediate pointer that points outside the array?
It's illegal, though it will work as you think it ought on the vast majority
of machines.
Consider a segmented architecture system and a malloc() that likes to return
blocks starting on segment boundaries. The compiler would need a special
patch to compute a - 1 correctly and then offset by one again, which is more
trouble to implement than it is worth. Therefore the standard allows it to
calculate an address pointing somewhere into the wilds, or to trap, hence
undefined behaviour.
 
E

Eric Sosman

Jon said:
Is the following code invalid C:

char *a = malloc(1);
a--;
a[1] = 3;

because there is an intermediate pointer that points outside the array?

This is Question 6.17 in the comp.lang.c Frequently Asked
Questions (FAQ) list at <http://c-faq.com/>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top