Pointer to pointer conversion

W

WaterWalk

Hello. When I practice pointers, I write code like the following:
int *pn1;
void **pv = (void **)&pn1;
*pv = malloc(sizeof(int));
*pn1 = 1;

It seems to work. But when I consult n1124(the draft c99 standard with
tc2), in section 6.3.2.3/7, it says:
"A pointer to an object or incomplete type may be converted to a
pointer to a different
object or incomplete type. If the resulting pointer is not correctly
aligned for the
pointed-to type, the behavior is undefined."

It seems this statement fits the above code. Since no document says
whether (void **) is properly aligned for (int **), is the above code
potentially dangerous?
 
I

Iman S. H. Suyoto

Pietro said:
Yes, but at 6.3.2.2/1, it says:

6.3.2.3 Pointers
1 A pointer to void may be converted to or from a pointer to any
incomplete or object type. A pointer to any incomplete or object
type may be converted to a pointer to void and back again; the
result shall compare equal to the original pointer.

the cast (void **) on &pn1 is not even necessary.

Moreover, I don't see the point of using pv to allocate room for pn1.

Why not just

pn1 = malloc(sizeof(int));

Even better:

pn1 = malloc(sizeof *pn1);
 
K

Keith Thompson

Eric Sosman said:
The fact that `void*' can be used as a "generic pointer"
leads some to think that `void**' is a "generic pointer-to-
pointer," but there is no such animal in C.

There is, sort of. You can use void* as a "generic
pointer-to-pointer" (but if you inadvertently assign a
pointer-to-something-else to it, the compiler won't catch your error).
 
W

WaterWalk

Hello. When I practice pointers, I write code like the following:
int *pn1;
void **pv = (void **)&pn1;
*pv = malloc(sizeof(int));
*pn1 = 1;

It seems to work. But when I consult n1124(the draft c99 standard with
tc2), in section 6.3.2.3/7, it says:
"A pointer to an object or incomplete type may be converted to a
pointer to a different
object or incomplete type. If the resulting pointer is not correctly
aligned for the
pointed-to type, the behavior is undefined."

It seems this statement fits the above code. Since no document says
whether (void **) is properly aligned for (int **), is the above code
potentially dangerous?

Thank you all. Now I know better this problem.
 

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

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top