|
From: John F. <jo...@ti...> - 2005-05-16 23:38:44
|
Well, close but not quite.
If you were to define dataToken as char ** in the calling function and
then call
someFunction(dataToken);
you'd still be using an undefined value to call the function, since you
haven't assigned the variable dataToken to anything yet. This would most
likely result in a segmentation fault down in the called function when
you dereference the pointer.
If the malloc just has to be located down in the called function, I
would have in the calling function:
char *dataToken;
...
someFunction(&dataToken);
then the called function would be as you have it,
int someFunction(char **dataTokenPtr) {
...
*dataTokenPtr = (char*) malloc(...)
...
strcmp("HTTP",*dataTokenPtr);
...
So then in the calling function the argument &dataToken (which is of
type char **) is certainly defined, and is simply the address of a
variable on the local stack, that variable being of type char *. The
malloc statement in the called function would then modify the value of
(char *) dataToken back up in the stack frame of the calling function.
But it becomes real hard to keep track of your memory allocation when
you have memory malloced in a different function than where you should
be freeing it. This is really a recipe for memory leaks when the program
gets big. This is why I would suggest mallocing in the same function
that decides that the string isn't needed anymore and frees it.
John
Stephen Ray wrote:
> Liam Whalen wrote:
> ...snip
>
>> When I call my parsing function I pass it a pointer to a char and
>> malloc memory inside the parsing function for the char. However when
>> I return from the parsing program the char that I passed it doesn't
>> point to the data parsed.
>>
>
>
> My understanding is that parameters to a function cannot be modified,
> ie. you cannot pass a pointer to a function and change the location the
> pointer points to. Instead, you must pass a pointer to a pointer.
>
> So then, you would have something like
> char **dataToken;
>
> then you call
> int someFunction(dataToken){
>
> in the function you would
> *dataToken = (char*) malloc(...)
>
> and then later you can use *dataToken to reference the malloc'ed memory.
>
> If any of this is wrong, I apologize. It's been awhile since I've
> actually used any C.
>
> Stephen
>
|