Unix Programming - Why the SEGFAULT in this code?

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > September 2004 > Why the SEGFAULT in this code?





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Why the SEGFAULT in this code?
RJGraham

2004-09-22, 9:21 pm

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 !!!
}
RJGraham

2004-09-22, 9:21 pm

Måns Rullgård wrote:
> RJGraham <null@null.com> writes:
>
>
[snip][vbcol=seagreen]
>
> strtok_r modifies the value of buf, hence the need for the double
> pointer. You should save the original value somewhere and pass that
> to free().
>
>
>
>

Yes, thanks.

I realized that just after posting, which always seems to happen ;)

-Randy
Nils O. Selåsdal

2004-09-22, 9:21 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..

Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com