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

Home Posts Topics Members FAQ

strlen in a for loop with malloc-ed char*

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 *reverse(char *s)
{
int i;
char *r;
if(!s) return NULL;//ERROR
r=calloc(strlen (s)+1,sizeof(ch ar));
if(!r) return NULL;
for(i=0;i<strle n(s);i++)
*(r+i) = *(s+strlen(s)-1-i);
return r;
}

--
it's not right. it's not even wrong
Nov 14 '05 #1
33 2970
On Tue, 19 Oct 2004 18:53:37 +0000, apropo wrote:
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? You calculate the strlen() many times, which really isn't needed char *reverse(char *s)
{
int i;
char *r; size_t len; if(!s) return NULL;//ERROR len = strlen(s);
r=calloc(len+1, sizeof(char)); if(!r) return NULL; for(i=0;i<len;i ++)
*(r+i) = *(s+len-1-i); return r;
}


Nov 14 '05 #2
apropo wrote:
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 *reverse(char *s)
{
int i;
char *r;
if(!s) return NULL;//ERROR
r=calloc(strlen (s)+1,sizeof(ch ar));
if(!r) return NULL;
for(i=0;i<strle n(s);i++)
*(r+i) = *(s+strlen(s)-1-i);
return r;
}


Computing something within a loop that is invarient is wasteful.
The length of "s" isn't changed by this function, so you might
consider taking it in as a const char * to reflect that. Anyway,
more normal would be to do:

size_t len = strlen(s);

And then use len where you are using strlen(s). It is possible
that the optimizer might fix this for you, but why ask for
trouble?

The code isn't "wrong", just burns CPU where it need not.
The calloc is also slightly wasteful, in that you are zeroing
out the memory you are about to fill in just to get the nul
termination, you could just have r[len] = '\0'; after mallocing it.
Whatever.

-David
Nov 14 '05 #3

"apropo" <fl***********@ yahoo.com> wrote

for(i=0;i<strle n(s);i++)
*(r+i) = *(s+strlen(s)-1-i);

Imagine that the string s is huge. Then remember how the computer will
implement strlen() (write the function yourself, if you are not sure).

Are you familiar with Big O notation for algorithms? This tells you how many
operations you need for a given size of input. For instance to multiply by
repeated adding is O(N); you need to add the numbers as often as the smaller
is large. To use the algorithm you were taught at primary school is O(log
N), since the numbers of operations you require goes up by the number of
digits. The adding algorithm is OK for numbers up to ten or so, but for
large numbers the primary school way is far superior.

Similarly, your code is OK for fairly short strings, but for long ones you
will slow things down considerably. Can you work out its Big O notation?
Nov 14 '05 #4
David Resnick wrote:

Computing something within a loop that is invarient is wasteful.
The length of "s" isn't changed by this function, so you might
consider taking it in as a const char * to reflect that.

Are some compilers sophisticated enough to be able to detect this
condition and optimize away that strlen() call?

Brian
Nov 14 '05 #5
Default User wrote:
David Resnick wrote:
Computing something within a loop that is invarient is wasteful.
The length of "s" isn't changed by this function, so you might
consider taking it in as a const char * to reflect that.
Are some compilers sophisticated enough to be able to detect this
condition and optimize away that strlen() call?


The compiler doesn't necessarily know what your strlen() does; after all
you can write it yourself!

Robert
Brian

Nov 14 '05 #6

On Tue, 19 Oct 2004, Robert Harris wrote:
Default User wrote:
David Resnick wrote:
Computing something within a loop that is invarient is wasteful.
The length of "s" isn't changed by this function, so you might
consider taking it in as a const char * to reflect that.


Are some compilers sophisticated enough to be able to detect this
condition and optimize away that strlen() call?


The compiler doesn't necessarily know what your strlen() does; after
all you can write it yourself!


Not in standard C. IIRC, attempting to redefine a standard library
function invokes undefined behavior. (And AFAIK it's quite possible that
the above optimization is the /only/ reason such redefinitions were made
undefined.)

-Arthur
Nov 14 '05 #7
Robert Harris wrote:
Default User wrote:
David Resnick wrote:
Computing something within a loop that is invarient is wasteful.
The length of "s" isn't changed by this function, so you might
consider taking it in as a const char * to reflect that.


Are some compilers sophisticated enough to be able to detect this
condition and optimize away that strlen() call?


The compiler doesn't necessarily know what your strlen() does; after
all you can write it yourself!


What do you mean? It knows its signature:

size_t strlen(const char *s)

Therefore it knows that it doesn't change s. It also knows what
strlen() does (as it is a standard library function).

Brian

Nov 14 '05 #8
"Default User" <fi********@boe ing.com.invalid > writes:
What do you mean? It knows its signature:

size_t strlen(const char *s)

Therefore it knows that it doesn't change s.


Not true. A function parameter's const-ness does not allowed the
compiler to assume that the function will not modify the
argument. It is perfectly valid for it to cast away the
const-ness and modify it anyway (as long as the object that it
refers to is not actually defined as const). `const' in function
parameters is a social contract between the caller and the
callee, not a constraint made by the standard.
--
Ben Pfaff
email: bl*@cs.stanford .edu
web: http://benpfaff.org
Nov 14 '05 #9
Ben Pfaff wrote:
"Default User" <fi********@boe ing.com.invalid > writes:
What do you mean? It knows its signature:

size_t strlen(const char *s)

Therefore it knows that it doesn't change s.


Not true. A function parameter's const-ness does not allowed the
compiler to assume that the function will not modify the
argument. It is perfectly valid for it to cast away the
const-ness and modify it anyway (as long as the object that it
refers to is not actually defined as const). `const' in function
parameters is a social contract between the caller and the
callee, not a constraint made by the standard.


Ok, good point. Looking at n689, it specifies what strlen() does, but
doesn't say that it is forbidden to change the string. It would be a
pretty perverse implementation with a poor QOS.

Brian

Nov 14 '05 #10

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

Similar topics

45
11726
by: Matt Parkins | last post by:
Hi, (I realise this probably isn't precisely the right group for this - could someone direct me to the appropriate group to post this question? - thanks !) I'm using Visual C++ 2005 Express Edition Beta (free download from MS - hooray!), and everything works fine, except I get warnings back on the use of some functions, strlen() for example, saying that the function has been deprecated - although they do still work (which is I guess...
12
4427
by: Nollie | last post by:
I need to write a couple of my own string manipulation routines (e.g. a strcpy() alternative that returns the number of chars copied). I've started with one of the simpler functions, strlen(). I've written a very simple version call StringLength(), but it performs significantly slower than its CRT counterparts. Here's my implementation: inline unsigned int StringLength( const char *pszString ) { unsigned int cch = 0;
7
3140
by: vjay | last post by:
I want to just create a linklist.The program below goes into an endless loop.The srange behaviour is that i can exit from the program if i create only two nodes.After two goes into infinite loop. #include<stdio.h> #include<stdlib.h> struct node { int data;
66
7785
by: roy | last post by:
Hi, I was wondering how strlen is implemented. What if the input string doesn't have a null terminator, namely the '\0'? Thanks a lot Roy
9
3563
by: No Such Luck | last post by:
I have a function which requires me to loop from the end of a string to the beginning on a char by char basis: int foo (char string) { unsigned int i; for(i = strlen(string); i >= 0; i--) { /* do something */
8
1664
by: Sheldon | last post by:
Hi, I have a problem that and the answer eludes me: I am converting a 2D array to a 1D array within a for loop that looks something like this: ii=0; for (i = 0; i < 300; i++) { for (j = 0; j < 250; j++) {
2
2264
by: Chris | last post by:
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>
53
717
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
11
3396
by: Bill Cunningham | last post by:
Strncat is supposed to be better than strcat for some reason I've read. Is this because of a potential buffer overflow? I have compiled properly and used strlen too and I just wonder what is the need to return a strlen? Has anyone used quite abit anyway the strlen function? Bill
31
470
by: Jean-Marc Bourguet | last post by:
jacob navia <jacob@nospam.comwrites: I'd first align and then use that. You may get a trap with unaligned access even on machine where unaligned access doesn't normally trap if you stump on a page boundary with the next page not mapped in memory. And some machine allows unaligned access but at a performance penality, which would be against the goal of using that trick.
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
9398
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
10156
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
9951
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,...
0
9832
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5275
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
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
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.