473,394 Members | 1,769 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,394 software developers and data experts.

Weird strlen behavior

Hi there,

I have been reading in this group for a while really enjoy this pool
of infinite c wisdom. :)

Anyway, I have question now. I have this little piece of code that is
giving me a headache.

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

/* Definitions */
#define STRING_LENGTH 12

/* Variables */
char str[STRING_LENGTH];
char *str1;
char *str2 = &str[0];
unsigned int i;

/* Main */
int main(void)
{
str1 = "Hello World!";

printf("String length: %d\n",strlen(str1));

for(i = 0u; i < strlen(str1); i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}

puts(str);

/* Wait for key */
getc(stdin);
return EXIT_SUCCESS;
}

The problem is the strlen(str1) expression. The code compiles fine
(with latest MinGW under XP) but running the executable it gives me
the following output:

String Length: 12
0
1
2
3
4
5
Hello

It seems to break out of the loop early, after 6 iterations instead of
12.

I replace the expression with something like this:

unsigned int length;

....

length = strlen(str1);

for(i = 0u; i < length; i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}

....

Then it works fine and runs 12 times and copies the entire string.

Any idea whats the problem here?

Thanks,
Chris

Mar 3 '07 #1
2 2242
Chris wrote:
Hi there,

I have been reading in this group for a while really enjoy this pool
of infinite c wisdom. :)

Anyway, I have question now. I have this little piece of code that is
giving me a headache.

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

/* Definitions */
#define STRING_LENGTH 12

/* Variables */
char str[STRING_LENGTH];
char *str1;
char *str2 = &str[0];
unsigned int i;

/* Main */
int main(void)
{
str1 = "Hello World!";

printf("String length: %d\n",strlen(str1));

for(i = 0u; i < strlen(str1); i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}

puts(str);

/* Wait for key */
getc(stdin);
return EXIT_SUCCESS;
}

The problem is the strlen(str1) expression. The code compiles fine
(with latest MinGW under XP) but running the executable it gives me
the following output:

String Length: 12
0
1
2
3
4
5
Hello

It seems to break out of the loop early, after 6 iterations instead of
12.

I replace the expression with something like this:

unsigned int length;

...

length = strlen(str1);

for(i = 0u; i < length; i++)
{
*str2++ = *str1++;
printf("%d\n",i);
}

...

Then it works fine and runs 12 times and copies the entire string.

Any idea whats the problem here?
You keep changing what str1 points to, and hence
changing the result of strlen(str1):

i = 0, strlen("Hello world!") = 12
i = 1, strlen("ello world!") = 11
i = 2, strlen("llo world!") = 10
i = 3, strlen("lo world!") = 9
i = 4, strlen("o world!") = 8
i = 5, strlen(" world!") = 7
i = 6, strlen("world!") = 6, that's all she wrote.

Incidentally, you should be glad that your loop stopped early.
The destination array str is twelve characters long, which is
enough room for a string of *eleven* characters plus the zero
end-marker. In your modified code you copy twelve characters
from "Hello world!" to the destination, but there is no end-
marker and the destination thus doesn't hold a proper string.
Pass this malformed string to a function expecting a well-
formed string (puts(), for example), and there's no telling
what will happen.

--
Eric Sosman
es*****@acm-dot-org.invalid
Mar 3 '07 #2
On Mar 3, 2:34 pm, Eric Sosman <esos...@acm-dot-org.invalidwrote:
You keep changing what str1 points to, and hence
changing the result of strlen(str1):

i = 0, strlen("Hello world!") = 12
i = 1, strlen("ello world!") = 11
i = 2, strlen("llo world!") = 10
i = 3, strlen("lo world!") = 9
i = 4, strlen("o world!") = 8
i = 5, strlen(" world!") = 7
i = 6, strlen("world!") = 6, that's all she wrote.
Doh! Thanks.
Incidentally, you should be glad that your loop stopped early.
The destination array str is twelve characters long, which is
enough room for a string of *eleven* characters plus the zero
end-marker. In your modified code you copy twelve characters
from "Hello world!" to the destination, but there is no end-
marker and the destination thus doesn't hold a proper string.
Pass this malformed string to a function expecting a well-
formed string (puts(), for example), and there's no telling
what will happen.
Thats correct. I always forget that little invisible sucker...

Thanks for the quick response.

Chris

Mar 3 '07 #3

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

Similar topics

21
by: sugaray | last post by:
hi, it just came up my mind that since we can get the length of any given string literal S with 'sizeof S-1', so, what's the merit of library function strlen()'s existence ? thanx in advance for...
81
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there...
33
by: apropo | last post by:
what is wrong with this code? someone told me there is a BAD practice with that strlen in the for loop, but i don't get it exactly. Could anyone explain me in plain english,please? char...
11
by: ncf | last post by:
Ok, I've been tring to resolve this issue for some time now (~1 day which is way longer than normal for me) to no avail. I am reading a file into a list in memory, using a "%" delimited file...
44
by: sam_cit | last post by:
Hi Everyone, I tried the following program unit in Microsoft Visual c++ 6.0 and the program caused unexpected behavior, #include <stdio.h> #include <string.h> int main() {
14
by: WStoreyII | last post by:
the following code is supposed to read a whole line upto a new line char from a file. however it does not work. it is producing weird results. please help. I had error checking in there for...
7
by: dtschoepe | last post by:
Hi, I am working on a project for school and I am trying to get my head around something weird. I have a function setup which is used to get an input from stdin and a piece of memory is created...
7
by: Duke | last post by:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv) { char *s = "hello strlen"; printf("%s has %d chars.\n", s, strlen(s)); //the above strlen function...
53
by: ¬a\\/b | last post by:
strlen is wrong because can not report if there is some error e.g. char *a; and "a" point to an array of size=size_t max that has no 0 in it
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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:
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...
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.