Can someone tell me why the code below should segfault at the line
indicated?
Also, why does strtok_r() require a **ptrptr and not a *ptr?
(Maybe this is a clue to my problem and misunderstanding of how strtok_r
is used...).
Thanks for any insight.
-Randy
PS: str arg is always guaranteed to point to a valid string < 127 chars
void getNameValuePairFromString(char * str, string & name, string & value)
{
char * buf = (char *) malloc(128);
char * tok = strtok_r(str, " =\n\r", &buf);
if (tok != NULL)
{
name = tok;
tok = strtok_r(NULL, " =\n\r", &buf);
if (tok != NULL)
value = tok;
}
free(buf); // seg fault here !!!
}
|
|
0
|
|
|
|
Reply
|
RJGraham
|
9/17/2004 11:06:25 PM |
|
On Fri, 17 Sep 2004 16:06:25 -0700, RJGraham wrote:
> Can someone tell me why the code below should segfault at the line
> indicated?
>
> Also, why does strtok_r() require a **ptrptr and not a *ptr?
Because how else could it change the pointer you supplied ?
> (Maybe this is a clue to my problem and misunderstanding of how strtok_r
> is used...).
>
> Thanks for any insight.
>
> -Randy
>
> PS: str arg is always guaranteed to point to a valid string < 127 chars
>
>
> void getNameValuePairFromString(char * str, string & name, string & value)
> {
You are changing the buf pointer with the calls to
strtok_r, so when you free it, buf doesn't point to
what you malloced.
Do;
char * buffer = (char *) malloc(128);
char *buf = buffer;
> char * tok = strtok_r(str, " =\n\r", &buf);
> if (tok != NULL)
> {
> name = tok;
> tok = strtok_r(NULL, " =\n\r", &buf);
> if (tok != NULL)
> value = tok;
> }
> free(buf); // seg fault here !!!
And;
free(buffer);
> }
You can probably avoid the malloc/free stuff alltogether, perhaps
just initializing buf to NULL suffices. Never used strtok, and my docs
doesn't do a very good job explaining the _r version though..
|
|
0
|
|
|
|
Reply
|
iso
|
9/18/2004 12:43:11 AM
|
|