View Full Version : how to use strstr
JeanC
20th August 2008, 15:36
Hello,
This code crashes with segfault
QString MainWindowImpl::getIp(QString line)
{
static char ip[1000], s[1000];
strcpy(s, line.toLocal8Bit().constData());
char *p1 = strstr(s, "client ") + 7, *p2 = ip;
while (*p1 && *p1 != ']')
*p2++ = *p1++;
*p2 = 0;
return ip;
If I change the line with strstr to:
char *p1 = s + 7, *p2 = ip;
all is well..
I know I can do things the qt way but I want to be portable with plain c strings.
Thanks.
Ginsengelf
20th August 2008, 15:42
I know I can do things the qt way but I want to be portable with plain c strings.
But you start with a QString anyway, so why not stay in the Qt realm?
Ginsengelf
JeanC
20th August 2008, 15:49
That is explained in the post.
But you start with a QString anyway, so why not stay in the Qt realm?
Ginsengelf
bunjee
20th August 2008, 16:06
I'd use strncpy to copy the exact length of the string.
And don't forget to add a NULL in the end, otherwise strstr won't likely work.
JeanC
20th August 2008, 17:38
int len = line.length();
strncpy(s, line.toLocal8Bit().constData(), len);
s[len] = 0;
char *p1 = strstr(s, "client ") + 7, *p2 = ip;
Still segfaults. I would have been very surprised if that was the solution, a normal strcpy wouldn't work and a strncpy would?
bunjee
20th August 2008, 18:58
did you try replacing
line.toLocal8Bit().constData()
by
line.toStdString().c_str()
Is it still crashing on that line :
char *p1 = strstr(s, "client ") + 7, *p2 = ip; ?
why do you declare
static char ip[1000], s[1000]; as static ?
JeanC
20th August 2008, 20:00
line.toStdString().c_str()
Just tried. Same result. From the posts I've read the only safe way is with those calls I used, as I understood it, all the rest leaves dangling pointers.
why do you declare
static char ip[1000], s[1000]; as static ?
Oops that's typo.
I thought Qt was about c++, I wonder what it takes to have it use charpointers, maybe some voodoo? Sigh. I don't understand why this is so hard. There's tons of c code out there, I have still useful code I wrote 25 years ago, I'm not gonna qchar or qbytearray all that. Sorry for the rant.
wysota
20th August 2008, 20:03
I know I can do things the qt way but I want to be portable with plain c strings.
How does using strstr on a string ripped from QString make you "portable with plain c strings"?
I'd check strstr() result for NULL and divide those statements separated by commas into two (or even three if you consider the "+7" part) real statements if I were you...
JeanC
20th August 2008, 20:48
Hey wysota,
I'd check strstr() result for NULL
I don't even have to try out the code, not checking for NULL from strstr is the error.
That is basic stuff, how can I forget that, I'm getting too old for this, I have to try another hobby like go fishing or so. :)
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.