473,396 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

counting string length using recursion?

Hi all,
As an exercise, I am trying to come up with a function to count the
length of a char* string using recursion. I came up with this:

int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

but it doesn't work. There is a core dump / illegal operation. I tried
to fix it by:

int count_length(char* s){
if(s == 0 || !*s)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

This seems to fix the problem and return the correct length. I tested
it with:

count_length(0);
count_length("12345");

My question is: Why is the first version not work? I though the "if(s
== 0)" check will catch the null pointer, no? Can someone explain to
me? Thanks!
Jul 22 '05 #1
8 10371
pembed2003 wrote:
[snip]
int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

but it doesn't work. There is a core dump / illegal operation.by:

[/snip]

The end of a char string is a 0 character. This routine tests for s==0
and will not catch the end of the string indicated by *s == 0. Thus, the
pointer s will keep moving through memory until it hits a region
that your process is not allowed to access. Then the programm crashes.
Best

Kai-Uwe Bux
Jul 22 '05 #2
pembed2003 wrote:
Hi all,
As an exercise, I am trying to come up with a function to count the
length of a char* string using recursion. I came up with this:

int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

but it doesn't work. There is a core dump / illegal operation. I tried
yes, because you never stop counting.
to fix it by:

int count_length(char* s){
if(s == 0 || !*s)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

This seems to fix the problem and return the correct length. I tested
it with:


yup. the test you have about now first checks to make sure that s is not
a null pointer, then checks to make sure that _what s points to_ is not
0, which denotes the end of the string.

for a clearer example, consider this:

if (s == 0) {
//s is null
}

if (*s == char(0)) { // note the cast for clarity
//s points to a null character - the end of a string
}

if you want my opinion, i'd recommend that you don't return 0 as the
length of a null pointer "string". null pointers are problematic (and
have obviously confused you slightly).

perhaps better would be:

int count_length(char* s){
assert(s != 0);

if (*s == '\0')
return 0;
else{
s++;
return 1 + count_length(s);
}
}

or if you do not want to assert, then return -1 or something. that is,
of course, unless you want to allow for null pointer "strings".

remember:
char* str = 0; // null pointer

is not the same as:
char* str = ""; // zero-length string

mark
Jul 22 '05 #3
pembed2003 wrote:
Hi all,
As an exercise, I am trying to come up with a function to count the
length of a char* string using recursion. I came up with this:

int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

but it doesn't work. There is a core dump / illegal operation. I tried
to fix it by:

int count_length(char* s){
if(s == 0 || !*s)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

This seems to fix the problem and return the correct length. I tested
it with:

count_length(0);
count_length("12345");

My question is: Why is the first version not work? I though the "if(s
== 0)" check will catch the null pointer, no? Can someone explain to
me? Thanks!


Because a null pointer is not the same as a nul character:

int strlen_r(const char* str)
{
return *str ? strlen_r(str + 1) + 1 : 0;
}

- Pete
Jul 22 '05 #4
Petec wrote:
<snip>

Because a null pointer is not the same as a nul character:

int strlen_r(const char* str)
{
return *str ? strlen_r(str + 1) + 1 : 0;
}


Note that my version treats a null pointer like the standard library strlen
does: it simply dereferences the null pointer. If you want to do some error
handling for that:

int strlen_r(const char* str)
{
if(!str) throw "null pointer in strlen_r()";
return *str ? strlen_r(str + 1) + 1 : 0;
}

Then clients can catch the error:

int main()
{
const char* str = "hello, world!";
try
{
std::printf("\"%s\" length: %d\n", str, strlen_r(s));
std::printf("NULL length: %d\n", str, strlen_r(0));
}
catch(const char* ex)
{
std::printf("%s\n", ex);
}

return 0;
}

- Pete
Jul 22 '05 #5
pembed2003 wrote:

Hi all,
As an exercise, I am trying to come up with a function to count the
length of a char* string using recursion. I came up with this:

int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

but it doesn't work. There is a core dump / illegal operation. I tried
to fix it by:

int count_length(char* s){
if(s == 0 || !*s)
return 0;
else{
s++;
return 1 + count_length(s);
}
}

This seems to fix the problem and return the correct length. I tested
it with:

count_length(0);
count_length("12345");

My question is: Why is the first version not work? I though the "if(s
== 0)" check will catch the null pointer, no? Can someone explain to
me? Thanks!


s is a pointer. Incrementing it moves to the next address. It will only be
zero after it wraps past its limit.

You need to test what s is pointing to:

int count_length(char* s){
if(!*s)
return 0;
// ...

Of course, this presumes that a valid (non NULL) string is passed in. If s can
be NULL, then your second version is most appropriate.

As a matter of clarity, it is more appropriate to write:

++s;

as opposed to:

s++;
Jul 22 '05 #6
"Petec" <x@x.x> wrote in message news:<sf******************@newsread1.news.pas.eart hlink.net>...
Petec wrote:
<snip>

Because a null pointer is not the same as a nul character:

int strlen_r(const char* str)
{
return *str ? strlen_r(str + 1) + 1 : 0;
}


Note that my version treats a null pointer like the standard library strlen
does: it simply dereferences the null pointer.


Thanks for everyone who answered my question:

A null pointer != A null character

Now another question for Petec:

You said the standard library strlen simply dereferences the null
pointer but won't that cause problem? Because the null pointer can not
be dereferenced right? In fact, I tried your version:

int strlen_r(const char* str)
{
return *str ? strlen_r(str + 1) + 1 : 0;
}

with:

strlen_r(0);

and the program crash. Can you explain?
Jul 22 '05 #7
pembed2003 wrote:
Now another question for Petec:

You said the standard library strlen simply dereferences the null
pointer but won't that cause problem? Because the null pointer can not
be dereferenced right?
Of course. The strlen function will crash the same way as Petec example
you tried. The second Petec example handles this problem and in case of
NULL pointer it throws out an exception.
In fact, I tried your version:

int strlen_r(const char* str)
{
return *str ? strlen_r(str + 1) + 1 : 0;
}

with:

strlen_r(0);

and the program crash. Can you explain?


Jul 22 '05 #8
Milan Cermak wrote:

pembed2003 wrote:
Now another question for Petec:

You said the standard library strlen simply dereferences the null
pointer but won't that cause problem? Because the null pointer can not
be dereferenced right?


Of course. The strlen function will crash the same way as Petec example
you tried. The second Petec example handles this problem and in case of
NULL pointer it throws out an exception.

To be precise, it probably have undefined behavior. That may be crash.
It may not be a crash. Expecting the system to bail out on UB is a
common error. Instead, the program may charge off and do all sorts of
fun things that don't involve crashing at all.


Brian Rodenborn
Jul 22 '05 #9

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

Similar topics

14
by: Mike N. | last post by:
Hello: I have a form that contains a multiple-select field that has 12 options in it. I would like the user to be able to select UP TO FOUR of those options. If they select more than four, I...
5
by: Anders K. Jacobsen [DK] | last post by:
Hi We have a rather large asp.net project with serveral utility projects (written in C#). Is there at tool out there which can give an estimate of the total amount of code lines all projects...
4
by: aaronfude | last post by:
Hi, Please consider the following class (it's not really my class, but it's a good example for my question): class Vector { int myN; double *myX; Vector(int n) : myN(n), myX(new double) { }...
14
by: ranjmis | last post by:
Hi all, Below is the code wherein I am initializing double dimentional array inside main with string literals. Now I want to display the strings using a function call to which I just want to...
7
by: Chris Lasher | last post by:
Hi all, How can one count all the permutations of a substring in a string? For a more concrete example, let's say targetstr = 'AAA' and probestr = 'AA' I want to consider how many times one...
34
by: Larry Hastings | last post by:
This is such a long posting that I've broken it out into sections. Note that while developing this patch I discovered a Subtle Bug in CPython, which I have discussed in its own section below. ...
7
by: peraklo | last post by:
Hello, there is another problem i am facing. i have a text file which is about 15000 lines big. i have to cut the last 27 lines from that file and create a new text file that contans those 27...
1
by: powerej | last post by:
I have gotten the part of counting how many words are in the string, but the vowels just seem alien to me. Ive tried so many things but never close to a correct answer. I know I need to use...
7
by: samelzoro | last post by:
here is a problem in recursion: unexpected result ? by this program I just want to convert xml dom's document object to xml-string. (for all browsers) //load a xml function...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.