Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

segfault

2 views
Skip to first unread message

xvart

unread,
Jan 13, 2007, 4:30:57 AM1/13/07
to
The *pch=0; causes this to segfault, my question is why, I can get it
to work replacing the "l" definition with "char
*l=strdup("hello;world;this;is;a;test;");", what is the issue here I
tried static as the data should then be on the heap, and again a seg
fault.... is this some page locking thing,


#include <stdio.h>
#include <string.h>
int main()
{
char *sptr;
char *pch;
char *l="hello;world;this;is;a;test;";
sptr=l;
pch=l;
while ( strchr(pch, ';')?(pch=strchr(pch, ';')):(pch=strchr(pch,
'\r')) ) {
*pch=0;
printf("%s\n",sptr);
sptr=++pch;
}
return 1;
}

Michael Mair

unread,
Jan 13, 2007, 7:54:32 AM1/13/07
to
xvart wrote:
> The *pch=0; causes this to segfault, my question is why, I can get it
> to work replacing the "l" definition with "char
> *l=strdup("hello;world;this;is;a;test;");", what is the issue here I
> tried static as the data should then be on the heap, and again a seg
> fault.... is this some page locking thing,

String literals are not guaranteed to be modifiable -- in
fact, you are better off thinking of string literals as
if they were of type "const char *" unless used as initialiser
for an array, i.e.
const char *l = "string";
is the safe and sensible way to access the string literal and
char l[] = "string";
is the way to obtain a modifiable string.

You can tweak gcc's behaviour using "-fwritable-strings" but
this is dangerous and leads to potential portability problems.


> #include <stdio.h>
> #include <string.h>
> int main()
> {
> char *sptr;
> char *pch;
> char *l="hello;world;this;is;a;test;";
> sptr=l;
> pch=l;
> while ( strchr(pch, ';')?(pch=strchr(pch, ';')):(pch=strchr(pch,
> '\r')) ) {

Note: This borders on unnecessary obfuscation.
pch = (strchr(pch, ';') ? strchr(pch, ';') : strchr(pch, '\r'))
gives you the same but is still not very clear.
In addition, this construct is not easily extensible in a way
that retains any vestige of clarity if you start looking for,
say, '\v' and '\t', too.
Consider giving clear names to your variables -- this helps others
and, if you come back to old code after a couple of months, years,
or decades, yourself.

Have a look at strcspn() and strpbrk(), too.

> *pch=0;
> printf("%s\n",sptr);
> sptr=++pch;
> }
> return 1;

Portable return values for main() are 0 and EXIT_SUCCESS and
EXIT_FAILURE from <stdlib.h>.

> }
>


Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.

xvart

unread,
Jan 13, 2007, 11:17:09 AM1/13/07
to
Thanks for the reply cleared up everything as to default behaviour, the
obfuscation is to confuse a friend.. having some fun at his expense,
cheap I know..
0 new messages