F
fix
Hi all,
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.
Is there any general rules that tell me when to allocate memory?
I thought I don't have to if it is a variable that's not a pointer, and
I have to if it is.
I am a bit confused about the arrays particularly.
In normal situations, memory is allocated for array[10] and I don't have
to do so, but if I want to use a pointer so that the array can be
dynamic, I shall use *array and allocate the amount of memory I want,
like array = malloc(sizeof(data_type) * number_of_item), right?
And if I am storing a "string" (char array) in a struct, what happens.
I declared it as:
typedef struct {
void *obj;
char key[];
} HashTableEntry;
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;
How do the program know how much memory have to be allocated for the
HashTableEntry? It seems that it is dynamically sized, it depends on the
char array key.
And one more thing is, I can't reverse the order of the two members, if
I do so, the program does not compile. Is there any link between the
problem I have said above?
Thanks all!
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.
Is there any general rules that tell me when to allocate memory?
I thought I don't have to if it is a variable that's not a pointer, and
I have to if it is.
I am a bit confused about the arrays particularly.
In normal situations, memory is allocated for array[10] and I don't have
to do so, but if I want to use a pointer so that the array can be
dynamic, I shall use *array and allocate the amount of memory I want,
like array = malloc(sizeof(data_type) * number_of_item), right?
And if I am storing a "string" (char array) in a struct, what happens.
I declared it as:
typedef struct {
void *obj;
char key[];
} HashTableEntry;
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;
How do the program know how much memory have to be allocated for the
HashTableEntry? It seems that it is dynamically sized, it depends on the
char array key.
And one more thing is, I can't reverse the order of the two members, if
I do so, the program does not compile. Is there any link between the
problem I have said above?
Thanks all!