473,770 Members | 1,799 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
33 2972
bd
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++)
Every time you go through the loop, you get the length of the string again.
Since it's not going to change, this is a huge waste of time (turns an O(n)
algorithm into an O(n^2) !). Save strlen(s) to a local variable once, then
use that instead.
*(r+i) = *(s+strlen(s)-1-i);
return r;
}


Nov 14 '05 #11
Default User wrote:

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.


A standard compliant strlen is not allowed to change the string.
If a function can do whatever it wants as long as the standard
does not specify that it cannot then it is impossible to write a
strictly conforming program that uses any standard functions.

In fact the standard only specifies what operators do, not what
they cannot do! It would in fact be impossible to write any strictly
conforming program at all with the possible exception of

int main(void)
{
return 0;
}

But then again, the standard does not specify completely what return
cannot do.

Relating to the point above. The compiler can optimise out calls to
strlen because it knows the implementation. In general it cannot do this
with functions unless it can deduce that no side effects are taking
place and that is impossible by just looking at the prototype. It is
possible (sometimes) if the compiler has access to the implementation of
a function.
--
Thomas.
Nov 14 '05 #12

"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote in message
news:Pi******** *************** ***********@uni x49.andrew.cmu. edu...

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.)


Ok.. so if i want to use my own 'strlen' (my_strlen) instead of standard
one(or any function defined by standard )can I not do that ?

Something like
#ifdef strlen
#undef strlen
#define strlen my_strlen

Cant afford to change all the places where i have called strlen !

- Ravi


-Arthur

Nov 14 '05 #13
Thomas Stegen wrote:
Relating to the point above. The compiler can optimise out calls to
strlen because it knows the implementation. In general it cannot do this
with functions unless it can deduce that no side effects are taking
place and that is impossible by just looking at the prototype. It is
possible (sometimes) if the compiler has access to the implementation of
a function.

It would also have to perform a bit heuristic to determin that calls
to strlen could be done fewer times than actual started. This can
quickly become nontrivial.
Nov 14 '05 #14
Ravi Uday wrote:
Ok.. so if i want to use my own 'strlen'
(my_strlen) instead of standard
one(or any function defined by standard )can I not do that ?

Something like
#ifdef strlen
#undef strlen
#define strlen my_strlen

Cant afford to change all the places where i have called strlen !


That doesn't do anything if strlen isn't implemented as a macro.
It doesn't have to be and I think that strlen usually isn't.

I don't know if redefining standard macros yields undefined behavior.
It seems like a bad idea.

--
pete
Nov 14 '05 #15
Hiho,

pete wrote:
Ravi Uday wrote:
Ok.. so if i want to use my own 'strlen'
(my_strlen) instead of standard
one(or any function defined by standard )can I not do that ?

Something like
#ifdef strlen
#undef strlen
#define strlen my_strlen

Cant afford to change all the places where i have called strlen !

Umh, the standard says strlen is a function so you cannot do this.
Apart from that: If you "hide" this nice trick of yours in a
general header file and other people are not aware of that then
they expect strlen (read: my_strlen) to behave like strlen (read:
strlen). If you really want to do something along these lines,
use a macro with a name like STRLEN or even a function pointer
called, for example, StrLenPtr. Thus, your intent becomes clearer.
Do not use names starting with str as these are reserved for
future library extensions.

That doesn't do anything if strlen isn't implemented as a macro.
Unfortunately, if you do it "right", it does:

#include <string.h>

#ifdef strlen
#undef strlen
#endif
#define strlen(STR) my_strlen(STR)

size_t my_strlen(const char *s)
{
return 0;
}

int main (void)
{
strlen("test");

return 0;
}

compiles and a look at the preprocessor output shows that
strlen("test");
becomes
my_strlen("test ");

You can have very funny effects if you use my_strlen() in very
rare cases as wrapper for strlen() but #define strlen before
you define my_strlen(). Then, everything works most of the time
but in some cases you have either recursive calls to my_strlen
without end or seemingly arbitrary results or whatever.
Nice trap.

It doesn't have to be and I think that strlen usually isn't.
Yep.
I don't know if redefining standard macros yields undefined behavior.
It seems like a bad idea.


Definitely! I'd even go as far and declare it a Bad Idea...
Cheers
Michael

Nov 14 '05 #16
Michael Mair wrote:

Hiho,

pete wrote:
Ravi Uday wrote:
Something like
#ifdef strlen
#undef strlen
#define strlen my_strlen
That doesn't do anything if strlen isn't implemented as a macro.


Unfortunately, if you do it "right", it does:


Thank you.

--
pete
Nov 14 '05 #17

In article <I5********@new s.boeing.com>, "Default User" <fi********@boe ing.com.invalid > writes:
Robert Harris wrote:
Default User wrote:

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.


The special case of standard functions aside, and the case of casting
away constness aside, this still isn't sufficient to optimize away
the call to a function. The function could have side effects besides
altering its parameters.

The *only* reason why an implementation might be able to optimize
away calls to standard functions is because it knows exactly what
they do. That's the only sufficient guarantee. (Note that this
also requires the restriction against redefining them.)

Of course, an implementation could introduce an extension - such as
a pragma - to denote "pure" functions which have no side effects and
make no use of external state and so could be similarly optimized
away when called repeatedly with the same parameters.[1] However,
standard C has no such facility.
1. Note that a function with no side effects must be a function only
of its input. Maintaining any kind of state between calls would be
a side effect. The restriction against using external state is
necessary to exclude things like clock(), which has no side effects
(except indirectly the one of taking non-zero execution time) but
should not be optimized away, as its return value changes over time.

--
Michael Wojcik mi************@ microfocus.com

The surface of the word "profession " is hard and rough, the inside mixed with
poison. It's this that prevents me crossing over. And what is there on the
other side? Only what people longingly refer to as "the other side".
-- Tawada Yoko (trans. Margaret Mitsutani)
Nov 14 '05 #18
In article <I5********@new s.boeing.com>, fi********@boei ng.com.invalid says...
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?


Not any of the majors, including gcc, lcc-win32 and MSVC. See a recent
thread on loop invariants in comp.programmin g for empirical data based
upon this same question.

--
Randy Howard (2reply remove FOOBAR)

Nov 14 '05 #19
In article <MP************ ************@ne ws.verizon.net> ,
ra*********@FOO verizonBAR.net says...
In article <I5********@new s.boeing.com>, fi********@boei ng.com.invalid says...
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?


Not any of the majors, including gcc, lcc-win32 and MSVC. See a recent
thread on loop invariants in comp.programmin g for empirical data based
upon this same question.


Correction, I didn't mean to imply that lcc is a "major" compiler, it
just happened to come up near the end of the thread and I included it
as a result.

--
Randy Howard (2reply remove FOOBAR)

Nov 14 '05 #20

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

Similar topics

45
11727
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
4428
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
7786
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
3397
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
9617
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
9454
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
10257
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...
0
10099
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10037
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
8931
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
6710
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.