473,765 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strstr crashes on NULL

Hi,
I have the following code:

#include <stdio.h>

int main(void){
char* str1 = "abc";
char* str2 = '\0';
if ( strstr(str1, str2) == NULL ){
printf("yes\n") ;
}
else{
printf("no\n");
}

return 0;
}

It crashes on strstr() call, so is it because none of strstr()
parameter can be NULL?

Jul 11 '07 #1
6 9444
In article <11************ **********@n2g2 000hse.googlegr oups.com>,
<li*****@hotmai l.comwrote:
I have the following code:
>#include <stdio.h>
>int main(void){
char* str1 = "abc";
char* str2 = '\0';
if ( strstr(str1, str2) == NULL ){
printf("yes\n") ;
}
else{
printf("no\n");
}

return 0;
}
It crashes on strstr() call, so is it because none of strstr()
parameter can be NULL?
Right. Your char* str2 = '\0' is setting str2 to a NULL pointer
instead of to an empty string, which would be "" or "\0";
'\0' happens to be an integral constant with value 0 and so is
a valid NULL pointer initializer (if strange). In C89 at least,
strstr() is not defined for the case of a NULL pointer
(but is defined for the case of a pointer to an empty string.)

--
I was very young in those days, but I was also rather dim.
-- Christopher Priest
Jul 12 '07 #2
li*****@hotmail .com wrote:
>
Hi,
I have the following code:

#include <stdio.h>
You're missing:
#include <string.h>
>
int main(void){
char* str1 = "abc";
char* str2 = '\0';
That's a bad way to write
char* str2 = NULL;

If you change that to
char* str2 = "";
then you can output "no".
if ( strstr(str1, str2) == NULL ){
printf("yes\n") ;
}
else{
printf("no\n");
}

return 0;
}

It crashes on strstr() call, so is it because none of strstr()
parameter can be NULL?
Yes.

--
pete
Jul 12 '07 #3
li*****@hotmail .com writes:
I have the following code:

#include <stdio.h>

int main(void){
char* str1 = "abc";
char* str2 = '\0';
if ( strstr(str1, str2) == NULL ){
printf("yes\n") ;
}
else{
printf("no\n");
}

return 0;
}

It crashes on strstr() call, so is it because none of strstr()
parameter can be NULL?
Yes. You may also be confused about the various meanings of "null".

In your declaration

char *str2 = '\0';

you're not setting str2 to point to an empty string; you're setting it
to a null pointer, which doesn't point to anything. If you wanted
str2 to point to a empty string, you could have declared:

char *str2 = "";

Normally the character constant '\0' is used to refer to a null
character, the character whose value is zero (sometimes called NUL
with one 'L'). This is the character used to mark the end of a
string.

But as it happens, the character constant '\0' is exactly equivalent
to the integer constant 0, and in this context it indicates a null
pointer, not a null character. Using '\0' in this context isn't
exactly wrong (the compiler is perfectly happy with it), but it's
misleading. If you want a null pointer, it's better to use the NULL
macro.

So, you can either declare:

char *str1 = "abc";
char *str2 = NULL;

(but then passing str2 to strstr invokes undefined behavior), or you
can declare:

char *str1 = "abc";
char *str2 = "";

In that case, strstr(str1, str2) will return the value of str1.

I suggest you take a look at sections 4, 5, and 6 of the comp.lang.c
FAQ, <http://www.c-faq.com/>.

You also need to add a '#include <string.h>' to your program, since
you're calling the strstr function. It may happen to work without it,
but the #include directive is *not* optional. (A note to my fellow
pedants: yes, he could declare strstr himself, but that would be
silly.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 12 '07 #4
On Jul 11, 6:33 pm, Keith Thompson <k...@mib.orgwr ote:
linq...@hotmail .com writes:
I have the following code:
#include <stdio.h>
int main(void){
char* str1 = "abc";
char* str2 = '\0';
if ( strstr(str1, str2) == NULL ){
printf("yes\n") ;
}
else{
printf("no\n");
}
return 0;
}
It crashes on strstr() call, so is it because none of strstr()
parameter can be NULL?

Yes. You may also be confused about the various meanings of "null".

In your declaration

char *str2 = '\0';

you're not setting str2 to point to an empty string; you're setting it
to a null pointer, which doesn't point to anything. If you wanted
str2 to point to a empty string, you could have declared:

char *str2 = "";

Normally the character constant '\0' is used to refer to a null
character, the character whose value is zero (sometimes called NUL
with one 'L'). This is the character used to mark the end of a
string.

But as it happens, the character constant '\0' is exactly equivalent
to the integer constant 0, and in this context it indicates a null
pointer, not a null character. Using '\0' in this context isn't
exactly wrong (the compiler is perfectly happy with it), but it's
misleading. If you want a null pointer, it's better to use the NULL
macro.

So, you can either declare:

char *str1 = "abc";
char *str2 = NULL;

(but then passing str2 to strstr invokes undefined behavior), or you
can declare:

char *str1 = "abc";
char *str2 = "";

In that case, strstr(str1, str2) will return the value of str1.

I suggest you take a look at sections 4, 5, and 6 of the comp.lang.c
FAQ, <http://www.c-faq.com/>.

You also need to add a '#include <string.h>' to your program, since
you're calling the strstr function. It may happen to work without it,
but the #include directive is *not* optional. (A note to my fellow
pedants: yes, he could declare strstr himself, but that would be
silly.)

--
Keith Thompson (The_Other_Keit h) k...@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Thanks.

My intention is that I use '\0' to initialize a string so that later I
can know its state. How about this code:

#include <string.h>
#include <stdio.h>

int main(void){
char str1[10], str2[10];

memset( str1, '\0', 10);
memset( str2, '\0', 10);

strcpy(str1, "abc");
if ( strstr(str1, str2) == NULL ){
printf("yes");
}
else{
printf("no");
}

return 0;
}

This code works fine on the same machine with same compiler, of
course I see "no". I tried commenting out string.h include, it still
works.

So does this mean it is really an un-expected behavior?

Jul 12 '07 #5
li*****@hotmail .com said:

<snip>
My intention is that I use '\0' to initialize a string so that later I
can know its state.
An empty string is very different to a null pointer.

const char *nullpointer = '\0';
const char *emptystring = "\0";

or, equivalently: const char *emptystring = "";
How about this code:

#include <string.h>
#include <stdio.h>

int main(void){
char str1[10], str2[10];

memset( str1, '\0', 10);
memset( str2, '\0', 10);
That's fine, but this works just as well:

char str1[10] = "", str2[10] = "";
strcpy(str1, "abc");
if ( strstr(str1, str2) == NULL ){
Yes, that's fine now.
This code works fine on the same machine with same compiler, of
course I see "no".
Yes - strstr is defined to return str1 if str2 is an empty string.
I tried commenting out string.h include, it still
works.
It is true that the program may give the appearance of continuing to
work when you chop off important bits, in much the same way that a used
car continues to work (for a while) with sand in the carburettor.
So does this mean it is really an un-expected behavior?
The code you posted this time is fine. Perfectly well-defined.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 12 '07 #6
santosh <sa*********@gm ail.comwrites:
linq...@hotmail .com wrote:
[...]
> strcpy(str1, "abc");
if ( strstr(str1, str2) == NULL ){
printf("yes");

Unless you terminate the string supplied to printf with a newline
character, '\n', or call fflush(stdout), your output is not guaranteed
to appear immediately
[...]

Actually, it's not guaranteed to appear *at all* unless the last
character you write to stdout is a new-line. It's
implementation-defined whether a text stream must end in a new-line.
The standard doesn't say what happens if a text stream does require a
trailing new-line and you don't provide one, so the behavior is
undefined; you might get no output at all, or demons might fly out of
your nose.

This is another of those things that will *probably* work just the way
you expect it to (the program will print "yes" or "no" without a
new-line), but if you write it correctly in the first place, you don't
have to worry about it.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 12 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1924
by: travis ray | last post by:
Hi, I have an extension in which a file object is created in python and passed down to a c extension which attempts to read from it or write to it. Writing to the file pointer seems to work okay, but reading from it results in EBADF. It also causes python to crash on exit. I've attached the minimal (I think) c code, python code, build script, build log, and run log. Any and all help is greatly appreciated.
5
2309
by: Rob Ristroph | last post by:
Hi, It's pretty unhelpful to post "I have a huge piece of code that crashes in strange places, what's the problem?" but that's basically my problem and I really am at my wit's end. The piece of code in question always crashes in an STL operation such as a vector.push_back, but the location of the crash changes as I change how various parts are handled in memory, i.e., make some things dynamically allocated instead of new'd. I know...
3
2460
by: Sean Bartholomew | last post by:
im trying to parse my email file located in my system library on my mac osx. i have a form online that, when filled and submitted, is sent to my email address. i need to parse the fields that were filled out ignoring all the ip and complicated stuff around it. for eg. im trying to at least get the first block of text that ONLY includes the fields and their values. char *tempBuf;
18
11851
by: Ramprasad A Padmanabhan | last post by:
In my program I am checking wether a emailid exists in a list I have in the complete_list a string like "<aa@abc.com> <ab@abc.com> <bc@abc.com> ... <xy@abc.com>" that is a string of emailids sorted Now I want to find out if another ID "<lm@abc.com>" exists in this list How is it possible to optimize the search given that the complete list
12
3313
by: Lars Langer | last post by:
Hi there, I'm new to this C - never the less - I'm trying to search a string for the occurence of a substring - However, I'm not very succesful since my use of the strstr function always returns NULL. But I know that there exsists such a substring, as I can see it with my own two eye when I print out the string to be searched. I added the code of the function (resolveResponse)and how I call this code - Calling the function:
24
12586
by: John Smith | last post by:
How to test whether strstr() returns a null pointer or not? Do I use something like the following? if(NULL != strstr(str1,str2)) That does not seem to work.
4
5415
by: smnoff | last post by:
I am trying to use the strstr function but it doesn't seem to work with a dynamically allocated string that I pass into a function. Specifically, I am using a Macromedia C-level extensibility and the JavaScript interpreter to write an extension. http://livedocs.macromedia.com/dreamweaver/8/extending/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=22_c_le2.htm#wp80297 ...
5
1543
by: Jeff | last post by:
ASP.NET 2.0 This code crashes. It generate this error: Value cannot be null. Parameter name: type I've created some custom web.config settings and this crash is related to accessing theme custom settings. This code is where the crash occur: _instance = (DAL)Activator.CreateInstance(Type.GetType(min.test.Config.Settings.msgElement.ProviderType));
3
2413
by: lovecreatesbea... | last post by:
I'm getting `warning: return discards qualifiers from pointer target type' at line 11 on this code from gcc. Some people suggested in old posts that this kind of warning can be suppressed by qualifying the return type with const. In this code it also can be removed by removing const from the first pointer parameter str. Are there better ways to do it, or does it deserve to do this? /* Search str for sub and return the pointer to the...
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5276
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.