malloc takes the number of bytes and returns a void* to the new memory. You can cast the void* to your struct using plain C-casts. You can get the size necessary using "sizeof( any struct )"
For some reasons, I cannot use extern "C". Also, I know that I need sizeof( any struct ) and a cast to GFSPPair. But the problems is the argument of GFSPPair, pair: new GFSPPair( pair )!
Does anybody have any idea how to exactly convert it to malloc calls?
You call malloc like this: struct GFSPPair* pair = malloc(sizeof(struct GFSPPair));
You shouldn't have to cast it -- malloc returns a void pointer for a reason.
Edit: the prefix "struct" is important -- you can't just do this:
1 2 3 4 5 6 7 8
struct foo {
int a;
int b;
};
int main()
{
foo bar;
1 2 3 4 5 6 7 8
struct foo {
int a;
int b;
};
int main()
{
struct foo bar;
But the problems is the argument of GFSPPair, pair: new GFSPPair( pair )!
together with:
I have a struct called GFSPPair. I made a reference to a GFSPPair instance called "pair" by:
... hm.. you don't mean by any chance that you just want a pointer pointing to the same object? Then it's in C++ and C the same: GFSPPair * p_pair = &pair;
If you want a real and full copy (not just a reference to the existing object), you have to use memcpy after you got your memory to copy the content of pair over to the memory where p_pair points to. Of course, your GFSPPair struct must noch contain any functions or constructors (C does not support functions in structs).
You shouldn't have to cast it -- malloc returns a void pointer for a reason.
ANSI C does implicit casting from void* to any pointer? That's odd, are you sure? I could swear it's only the other way around.
Edit: the prefix "struct" is important -- you can't just do this:
Or use the C-typical typedef idiom typedefstruct { ... } foo;.
@imi,
Excerpt from linux/Documentation/CodingStyle:
Chapter 14: Allocating memory
The kernel provides the following general purpose memory allocators:
kmalloc(), kzalloc(), kcalloc(), and vmalloc(). Please refer to the API
documentation for further information about them.
The preferred form for passing a size of a struct is the following:
p = kmalloc(sizeof(*p), ...);
The alternative form where struct name is spelled out hurts readability and
introduces an opportunity for a bug when the pointer variable type is changed
but the corresponding sizeof that is passed to a memory allocator is not.
Casting the return value which is a void pointer is redundant. The conversion
from void pointer to any other pointer type is guaranteed by the C programming
language.
I know that's kmalloc() and not malloc() but still, I'm fairly sure the Linux programmers know what they're talking about. You don't have to cast a void pointer to another type of pointer because the compiler does that for you. I mean, I guess if you want to it's ok -- but it's redundant code. I don't see that a compiler would optimize that out for you, either.