In C, a void*
is implicity convertible to a T*
where T
is any type. From section 6.3.2.3 Pointers of the C99 standard:
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.
malloc()
returns a void*
and is assignable without casting to head
, a struct node*
. This is not true in C++, so I suspect a C++ compiler is being used to compile this C code.
For example:
#include <stdlib.h>
int main()
{
int* i = malloc(sizeof(*i));
return 0;
}
when compiled with:
gcc -Wall -Werror -pedantic -std=c99 -pthread main.c -o main
emits no errors. When compiled with:
g++ -Wall -Werror -pedantic -std=c++11 -pthread main.cpp -o main
emits:
main.cpp: In function 'int main()':
main.cpp:5:31: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
Additionally, the onetwothree()
function is not allocating memory correctly. It allocates one struct node
only:
head = malloc(sizeof(struct node));
and then, eventually, dereferences head->next->next
which is undefined behaviour. An individual malloc()
is required for every struct node
.
Remember to free()
what was malloc()
d.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…