473,804 Members | 3,031 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comments on my code?

Hi-

I am learning C from some old lecture notes, but they don't have
solutions so I'd like some feedback on my code if anyone has the time.

This is an exercise: "Write a program to trim any leading whitespace
from a string and return a newly allocated buffer containing the trimmed
string. Don't forget to handle errors."

main(argc, argv)
int argc; char **argv;
{
char *strtrim(), *r=0;
puts(argc>1 && (r=strtrim(*++a rgv)) ? r : "Unspecifie d error");
free(r);
}

/* trims initial whitespace */
char *strtrim(s)
char *s;
{
char *r, *malloc();
for( ; isspace(*s); s++);
r=malloc(strlen (s)+1);
if(r)
strcpy(r,s);
return r;
}

This looks OK to me and works correctly, but the compiler produces some
mysterious warnings about conflicting definitions that I don't really
understand.
--
How come we never talk anymore?
Sep 1 '07
28 1691
On Sep 1, 10:33 pm, Harald van D k <true...@gmail. comwrote:
Francine.Ne...@ googlemail.com wrote:
On Sep 1, 8:22 pm, Keith Thompson <ks...@mib.orgw rote:
Harald van D k <true...@gmail. comwrites:
Platonic Solid wrote:
char *r, *malloc(), *strcpy();
On the contrary, I've declared malloc correctly and store its return
value in a char *.
No, you haven't declared malloc correctly.
Specifically, malloc returns void*, not char*, and it takes an
argument of type size_t. Since you didn't declare the argument type,
something as simple as malloc(42) invokes undefined behavior, since
you're passing an argument of type int.
If you had declared it correctly as
void *malloc(size_t) ;
then a call like malloc(42) would implicitly convert the argument to
size_t -- and a call with a non-numeric argument would trigger an
error message.
Am I right in thinking that first standard promotions would apply, and
only then would the result be converted to size_t?

Compare these functions:

unsigned short f1 (x)
unsigned short x;
{
return x;

}

unsigned short f2 (unsigned short x)
{
return x;

}

int main(void) {
unsigned short x = 3;
return f1(x) - f2(x);

}

The call to f1 results in x being promoted to int (or unsigned int,
depending on the system), and then converted back to unsigned short. The
call to f2 does not cause x to undergo any promotion to int.
That's interesting... so there could in fact be situations when using
K&R style functions could shorten your code, if you were able to take
advantage of edge effects for promotion versus conversion.
The given
declaration of malloc falls in the same category as f2, not f1. However, I
would be very surprised to find an implementation for which the end result
is any different for integer types.
Sep 1 '07 #21
On Sat, 1 Sep 2007 20:35:10 +0200 (CEST), Platonic Solid
<pl*****@mailin ator.comwrote:
>On 1 Sep 2007 at 16:42, CBFalconer wrote:
>Platonic Solid wrote:
>>>
... snip ...
>>>
OK, so that explains why strcpy produces a warning as it returns
char * and not int. But the compiler also complains about malloc
(I specifically supply the return type for that) and strlen, which
returns int so should be OK by Q 1.25.

You didn't give code, so we can't make suggestions.

On the contrary, I posted my code, but here it is again:

main(argc, argv)
int argc; char **argv;
{
char *strtrim(), *r=0;
puts(argc>1 && (r=strtrim(*++a rgv)) ? r : "Unspecifie d error");
free(r);
}

/* trims initial whitespace */
char *strtrim(s)
char *s;
{
char *r, *malloc(), *strcpy();
for( ; isspace(*s); s++);
r=malloc(strlen (s)+1);
if(r)
strcpy(r,s);
return r;
}

(I've made one fix, by putting in the correct return type for strcpy)

>If you have problems with malloc you are probably a) casting the
return or b) failing to include <stdlib.hor c) capturing the return
value in other than a pointer or d) using a C++ compiler.

On the contrary, I've declared malloc correctly and store its return
value in a char *.
No you didn't. If your notes are as old as they appear, they may say
malloc returns a char*. Unfortunately, that hasn't been true for over
15 years.
>
I'm not sure what to do about people's advice that some of the syntax in
the lecture notes is now old-fashioned - as it still seems to compile
just fine, I'm tempted to stick with what I know.
Old need not be bad but in this case it is hurting you more than
helping.
Remove del for email
Sep 2 '07 #22
On Sat, 1 Sep 2007 16:23:39 +0200, "Peter J. Holzer"
<hj*********@hj p.atwrote:
>On 2007-09-01 13:26, jacob navia <ja***@jacob.re mcomp.frwrote:
>Platonic Solid wrote:
>>On 1 Sep 2007 at 12:53, jacob navia wrote:
P.S. What happens when s is NULL?

If you look carefully I check argc>1, so it never gets called with s
null.

Sure, but is strtrim only for this particular call?
In that case a function is not necessary!

What happens when you call strlen(NULL)?
The C Standard says this about the function strlen:

<quote>
1 #include <string.h>
size_t strlen(const char *s);

2 The strlen function computes the length of the string pointed to by
s.

3 The strlen function returns the number of characters that precede
the terminating null character.
</quote>

Since a NULL pointer points to "nothing", it cannot point to anything
that includes a "terminatin g null character". Therefore, the behavior
(of strlen(NULL)) is undefined.

Best regards
--
jay
Sep 2 '07 #23
On Sat, 1 Sep 2007 14:01:58 +0200 (CEST), Platonic Solid
<pl*****@mailin ator.comwrote:
>Hi-

I am learning C from some old lecture notes, but they don't have
solutions so I'd like some feedback on my code if anyone has the time.

This is an exercise: "Write a program to trim any leading whitespace
from a string and return a newly allocated buffer containing the trimmed
string. Don't forget to handle errors."

main(argc, argv)
int argc; char **argv;
The lecture notes must be very old. This method of definition, while
still legal, fell out of style before 1990.
>{
char *strtrim(), *r=0;
puts(argc>1 && (r=strtrim(*++a rgv)) ? r : "Unspecifie d error");
Since the requirement did not specify handling errors in a user
friendly way, I guess this qualifies.
free(r);
}

/* trims initial whitespace */
char *strtrim(s)
char *s;
{
char *r, *malloc();
for( ; isspace(*s); s++);
r=malloc(strlen (s)+1);
Since there is no prototype for strlen, a C89 compiler is required to
assume that it returns an int. Since the previous declaration for
malloc was not a prototype, the compiler is required to assume it
takes an int for its only argument. Since malloc actually takes a
size_t which need not be an (unsigned) int, this invokes undefined
behavior.

It is only the coincidence that char* and void* must have the same
representation that might prevent further undefined behavior. If your
compiler and run-time library treat void* special, such as returning
it in a unique register, that prevention just evaporated.

Why are you lying to the compiler and not including the headers with
the correct prototypes?
if(r)
strcpy(r,s);
return r;
}

This looks OK to me and works correctly, but the compiler produces some
mysterious warnings about conflicting definitions that I don't really
understand.
How are we supposed to explain them if you won't tell us what they
say?
Remove del for email
Sep 2 '07 #24
Barry Schwarz wrote, On 02/09/07 17:27:
On Sat, 1 Sep 2007 14:01:58 +0200 (CEST), Platonic Solid
<pl*****@mailin ator.comwrote:
>Hi-

I am learning C from some old lecture notes, but they don't have
solutions so I'd like some feedback on my code if anyone has the time.

This is an exercise: "Write a program to trim any leading whitespace
from a string and return a newly allocated buffer containing the trimmed
string. Don't forget to handle errors."

main(argc, argv)
int argc; char **argv;

The lecture notes must be very old. This method of definition, while
still legal, fell out of style before 1990.
Well, it took a little while for all implementations to support the ANSI
standard, but basically true.
>{
char *strtrim(), *r=0;
puts(argc>1 && (r=strtrim(*++a rgv)) ? r : "Unspecifie d error");

Since the requirement did not specify handling errors in a user
friendly way, I guess this qualifies.
> free(r);
}

/* trims initial whitespace */
char *strtrim(s)
char *s;
{
char *r, *malloc();
for( ; isspace(*s); s++);
r=malloc(strlen (s)+1);

Since there is no prototype for strlen, a C89 compiler is required to
assume that it returns an int.
True, and it means the call invokes undefined behaviour.
Since the previous declaration for
malloc was not a prototype, the compiler is required to assume it
takes an int for its only argument.
Misleading, although true in this case. The compiler is required to
assume that it takes whatever it is given. As the compiler has assumed
strlen returns an int it wll make the value of strlen(s)+1 an int as
well and so assume malloc takes an int. Had there been a correct
prototype for strlen in place then it would have been "legal" although
very bad practice. Well, legal if the return type of malloc had been
specified as void* instead of incorrectly being specified as char*.
Since malloc actually takes a
size_t which need not be an (unsigned) int, this invokes undefined
behavior.
True.
It is only the coincidence that char* and void* must have the same
representation that might prevent further undefined behavior. If your
compiler and run-time library treat void* special, such as returning
it in a unique register, that prevention just evaporated.

Why are you lying to the compiler and not including the headers with
the correct prototypes?
Because he is working from notes that pre-date the standard?
> if(r)
strcpy(r,s);
return r;
}

This looks OK to me and works correctly, but the compiler produces some
mysterious warnings about conflicting definitions that I don't really
understand.

How are we supposed to explain them if you won't tell us what they
say?
Well, of you have probably explained a lot of the problems the compiler
was warning about :-)
--
Flash Gordon
Sep 2 '07 #25
On Sat, 01 Sep 2007 13:06:55 -0700, Fr************@ googlemail.com
wrote:
>On Sep 1, 8:22 pm, Keith Thompson <ks...@mib.orgw rote:
>Harald van D k <true...@gmail. comwrites:
Platonic Solid wrote:
char *r, *malloc(), *strcpy();
>On the contrary, I've declared malloc correctly and store its return
value in a char *.
No, you haven't declared malloc correctly.

Specifically , malloc returns void*, not char*, and it takes an
argument of type size_t. Since you didn't declare the argument type,
something as simple as malloc(42) invokes undefined behavior, since
you're passing an argument of type int.

If you had declared it correctly as
void *malloc(size_t) ;
then a call like malloc(42) would implicitly convert the argument to
size_t -- and a call with a non-numeric argument would trigger an
error message.

Am I right in thinking that first standard promotions would apply, and
only then would the result be converted to size_t?
Since 42 is already an integer, what standard promotions are you
referring to? If the argument had been an expression with operators,
the final value of the expression would have been converted to size_t.
If the process of evaluating the expression required standard
promotions, they would be performed first. However, the expression
consisted of a single short int variable, then I don't believe the
standard promotions are needed to convert the short value to a size_t
value (n1124, section 6.3.1.1, footnote 48).
Remove del for email
Sep 3 '07 #26
Barry Schwarz <sc******@doezl .netwrites:
On Sat, 01 Sep 2007 13:06:55 -0700, Fr************@ googlemail.com
wrote:
[...]
>>Am I right in thinking that first standard promotions would apply, and
only then would the result be converted to size_t?

Since 42 is already an integer, what standard promotions are you
referring to?
[...]

Ahem. Yes, 42 is an integer, but the relevant point is that it's an
int. (int is one of several integer types.)

--
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"
Sep 3 '07 #27
Keith Thompson wrote:
>
Barry Schwarz <sc******@doezl .netwrites:
On Sat, 01 Sep 2007 13:06:55 -0700, Fr************@ googlemail.com
wrote:
[...]
>Am I right in thinking that first
standard promotions would apply, and
only then would the result be converted to size_t?
Since 42 is already an integer, what standard promotions are you
referring to?
[...]

Ahem. Yes, 42 is an integer, but the relevant point is that it's an
int. (int is one of several integer types.)
But, there are no promotions
that would apply to an argument expression of type int,
prior to conversion to the parameter's type of size_t,
as in what Francine.Neary replied to:

"If you had declared it correctly as
void *malloc(size_t) ;
then a call like malloc(42) would implicitly convert the argument to
size_t -- and a call with a non-numeric argument would trigger an
error message."

--
pete
Sep 3 '07 #28
pete <pf*****@mindsp ring.comwrites:
Keith Thompson wrote:
>Barry Schwarz <sc******@doezl .netwrites:
On Sat, 01 Sep 2007 13:06:55 -0700, Fr************@ googlemail.com
wrote:
[...]
>>Am I right in thinking that first
standard promotions would apply, and
only then would the result be converted to size_t?

Since 42 is already an integer, what standard promotions are you
referring to?
[...]

Ahem. Yes, 42 is an integer, but the relevant point is that it's an
int. (int is one of several integer types.)

But, there are no promotions
that would apply to an argument expression of type int,
prior to conversion to the parameter's type of size_t,
as in what Francine.Neary replied to:
[snip]

My point was that Barry was glossing over the disinction between 'int'
and 'integer'.

--
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"
Sep 3 '07 #29

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

Similar topics

4
3381
by: Sims | last post by:
Hi, I proud myself in having good comments, (/**/, // etc...), all over my scripts as well as a very descriptive section at the beginning of the script. No correct me if i am wrong but php must still 'read' those comments? So, do comments technically slow the whole process? Or is the loss of CPU/Time/memory so negligible that i do not need to worry about it.
17
2755
by: lkrubner | last post by:
I've got a PHP application that's 2 megs in size. Of that, my guess is 200k-400k is comments. Do they impose a performance hit? I've been postponing any kind of optimization, but at some point I'll have to do it. Is taking out the comments worth it? Of all the optimizations I can do, where should it rank?
28
3466
by: Benjamin Niemann | last post by:
Hello, I've been just investigating IE conditional comments - hiding things from non-IE/Win browsers is easy, but I wanted to know, if it's possible to hide code from IE/Win browsers. I found <!> in the original MSDN documentation, but this is (although it is working) unfortunately non-validating gibberish. So I fooled around trying to find a way to make it valid. And voila: <!--><!><!-->
10
2102
by: Monk | last post by:
Hi, Have a query regarding comments that extend over multiple-lines. Would like to know if the standard's view of this, so that we can create a code which doesn't run into compiler specific issues. 1. A normal comments is /* comment text */ 2. A multiple line comment is
40
4649
by: Edward Elliott | last post by:
At the risk of flogging a dead horse, I'm wondering why Python doesn't have any multiline comments. One can abuse triple-quotes for that purpose, but that's obviously not what it's for and doesn't nest properly. ML has a very elegant system for nested comments with (* and *). Using an editor to throw #s in front of every line has limitations. Your editor has to support it and you have to know how to use that feature. Not exactly...
98
4632
by: tjb | last post by:
I often see code like this: /// <summary> /// Removes a node. /// </summary> /// <param name="node">The node to remove.</param> public void RemoveNode(Node node) { <...> }
2
7342
by: beatTheDevil | last post by:
Hey guys, As the title says I'm trying to make a regular expression (regex/regexp) for use in removing the comments from code. In this case, this particular regex is meant to match /* ... */ comments. I'm using Ruby v.1.8.6 Here's my regex: multiline_comments = /\/\*(.*?)\*\// When I try myStr.gsub(multiline_comments, "")
2
5389
by: mad.scientist.jr | last post by:
In .NET 2.0, is there any way to include comments in the aspx file that do not get rendered to the client (ie no <!-- -->) ? When I try to include C# comments in a code block in an aspx page, like this: <% // ******************************************************* // CHANGE HISTORY: // DATE USER CHANGE
6
12001
by: Marjeta | last post by:
I was trying to compare a particular trigger on multiple servers. First I tried phpMyAdmin to script the trigger code, which unfortunately only worked on one server that has newer version of phpMyAdmin... Then I used mysqldump, which scripted trigger code on all the servers, bur with comments around all the trigger related code: phpMyAdmine scripted trigger code without comments. Why are those comments there? I searched thru...
0
9706
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
9579
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
10326
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
10317
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
10075
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...
1
7615
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
5520
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...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
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.