Re: Allocating memory for struct - when?
From: Old Wolf (oldwolf_at_inspire.net.nz)
Date: 05/03/04
- Next message: Prashanth Badabagni: "Printing "hello , wolrd" with out using semicolon"
- Previous message: Old Wolf: "Re: register variable"
- In reply to: fix: "Allocating memory for struct - when?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 2 May 2004 22:55:21 -0700
fix <fix@here.com> wrote:
> I am writing a program using some structs, it is not running and I
> believe it is because there's some memory leak - the debugger tells me
> that the code causes the problem is in the malloc function.
> typedef struct {
> void *obj;
> char key[];
> } HashTableEntry;
BTW, you can't have arrays of these.
> What I do to initialize the object is:
>
> HashTableEntry *hte = malloc(sizeof(HashTableEntry));
> // "key" is a defined char array
> strcpy(hte->key, key);
> hte->obj = NULL;
What you should be doing is:
HashTableEntry *hte = malloc(strlen(key) + 1 + sizeof *hte);
strcpy(hte->key, key);
hte->obj = NULL;
Note that sizeof(*hte) is the same as sizeof(void*), the member "key"
does not have a size that the compiler knows about. You won't be
able to access the size of the entry later on in your code.
Because of this, you can't safely put a new value into the key (unless
it has the same length). So I would consider making key "const char"
instead of "char" (and casting it in the call to strcpy).
> And one more thing is, I can't reverse the order of the two members
Obviously not, how would the compiler know how much memory to
leave before the start of "obj" ?
If this is all confusing to you, you might want to consider
the other poster's suggestion of having "char *key;" and allocating
key with malloc too; although it seems to me that this is a perfect
example of a situation that flexible array members were designed for.
- Next message: Prashanth Badabagni: "Printing "hello , wolrd" with out using semicolon"
- Previous message: Old Wolf: "Re: register variable"
- In reply to: fix: "Allocating memory for struct - when?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|