K
Kamus of Kadizhar
This is probably pretty silly for those in the know, but it's been a while
since I've muddled about with malloc....
I have the following snippet of code:
char *letters_array[6];
......
int fill_letters(char *letterString,char *buffer) {
letterString = malloc(strlen(buffer)+1);
sprintf(letterString,"%s",buffer);
printf("fill: >%s<, %d\n",buffer,strlen(buffer)+1);
}
int load_default_charset() {
printf("in load_default_charset\n");
fill_letters(letters_array[0],"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
printf("filled: >%s<,\n",letters_array[0]);
...
return TRUE;
}
It seems that the memory allocated in fill_letters is being released as
soon as that function returns (the printf in load_default_charset shows
(NULL) for letters_array[0]). I would have thought that since I'm passing
pointers the malloc would be "sticky" and not be freed until a call to
free().
So, how do I rewrite the code to insure that the memory remains allocated?
I could pass just the index for letters_array, but for maintenance and
readability I would prefer to pass the pointer itself.
--Kamus
since I've muddled about with malloc....
I have the following snippet of code:
char *letters_array[6];
......
int fill_letters(char *letterString,char *buffer) {
letterString = malloc(strlen(buffer)+1);
sprintf(letterString,"%s",buffer);
printf("fill: >%s<, %d\n",buffer,strlen(buffer)+1);
}
int load_default_charset() {
printf("in load_default_charset\n");
fill_letters(letters_array[0],"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
printf("filled: >%s<,\n",letters_array[0]);
...
return TRUE;
}
It seems that the memory allocated in fill_letters is being released as
soon as that function returns (the printf in load_default_charset shows
(NULL) for letters_array[0]). I would have thought that since I'm passing
pointers the malloc would be "sticky" and not be freed until a call to
free().
So, how do I rewrite the code to insure that the memory remains allocated?
I could pass just the index for letters_array, but for maintenance and
readability I would prefer to pass the pointer itself.
--Kamus