473,795 Members | 3,151 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Crazy stuff

If I have this(please bear with me - this is a case of a former java
guy going back to C ;-)

int main () {
char *tokconvert(cha r*);
char str[] = "dot.delimited. str";
char *result;

result = tokconvert(str) ;
return 0;
}

char *tokconvert(cha r *strToConvert) {

char *token;
char *tokDelim =",.";

token=strtok(st rToConvert, tokDelim);

while(token != NULL) {
printf("Token -> %s \n", token);
token=strtok(NU LL, tokDelim);
}
}

the thing compiles and runs fine, however if I declare char *str =
"dot.delimited. str" (instead of char str[] = "dot.delimited. str") the
whole thing falls on its ass real bad (bus error) - strtok is defined
as char *strtok(char *, const char *) - what's going on?

more craziness: if I declare/initialise

char *str;
str = strdup("dot.del imited.str)

inside tokconvert (instead of main) and pass that to strtok - it runs
fine!!

any thoughts are most welcome..

chumbo.

P.S.
btw this is on FreeBSD 5.1.2 (using gcc 3.3.3)
Nov 14 '05
32 1989
On Mon, 15 Nov 2004 04:09:47 +0000, Dave Thompson wrote:

....
Huh? Unless I completely misunderstand what you are saying:
while the C standard does not specify implementation techniques, and
so can't topically rely on "the stack", on every machine I know of
that has a "processor stack segment", or indeed just a "processor
(memory) stack" anywhere, it was designed to be and in fact is used
for C (and other HLL) function-invocation frames in a stack fashion.

Well, the 6502 processor, which certainly does have C compilers targetting
it, has a 256 byte processor stack. I suspect the C compilers don't use
that to hold automatic variables.

Lawrence
Nov 14 '05 #21
In article <jm************ *************** *****@4ax.com>,
Dave Thompson <da************ *@worldnet.att. net> wrote:
On Sun, 7 Nov 2004 05:58:35 +0000 (UTC), dj******@csclub .uwaterloo.ca
(Dave Vandervies) wrote:
The array is in the automatic-allocation space (we can call this "the
stack", but we prefer not to, because the function-invocation stack that
it exists in is not the same stack as the "processor' s stack segment"
stack (which need not even exist) that people typically assume we're
talking about),

Huh? Unless I completely misunderstand what you are saying:
while the C standard does not specify implementation techniques, and
so can't topically rely on "the stack", on every machine I know of
that has a "processor stack segment", or indeed just a "processor
(memory) stack" anywhere, it was designed to be and in fact is used
for C (and other HLL) function-invocation frames in a stack fashion.


This is true, but not what I was saying (or at least not what I intended
to say).

The C (and other HLL) function-invocation stack is an abstract thing on
which continuations[1], automatic variables, and possibly a few things I'm
not thinking of live. The fact that, where they exist, hardware-assisted
stack mechanisms are universally used to (and, in fact, designed to)
implement this doesn't mean they're the same thing; one is a construct
of the language being implemented, and one is the back-end mechanism
used to implement it.

Note that (relevant to the subject, but not to your comments if
I'm understanding them correctly) even on systems without such a
hardware-assisted mechanism (I believe older IBM systems are the
canonical example, though I'd probably get the details wrong if I tried
to remember them) the invocation records (implemented as, say, a linked
list of freestore-allocated invocation frames) need to look, feel, and
smell like a stack - this is an obvious example of a function-invocation
stack not being implemented with a hardware stack.
dave

[1] That is, what to do when the function finishes (including what to
do with the return value, if there is one). Typically this is
implemented as a machine address referring to the point in the calling
code immediately after the actual subroutine call, where the return
value is handled appropriately and the rest of the caller continues
to run.

--
Dave Vandervies dj******@csclub .uwaterloo.ca
Perhaps the original version of the program worked.
OK, this takes us *way* off topic for any computer related newsgroup, but
you've got to admit its a theoretical possibility. --Ken Hagan in comp.arch
Nov 14 '05 #22
"Malcolm" <ma*****@55bank .freeserve.co.u k> wrote in message
news:cm******** *@news7.svr.pol .co.uk...

"Jack Klein" <ja*******@spam cop.net> wrote
Furthermore, C does not define any such thing as "read-only memory".
C does not define any such thing as "read-write memory".

That is true, but does not apply here. The result of attempting to
modify a string literal is undefined behavior. This is true not
because the type of the string literal is array of const char, but
because the C standard specifically states that it is so.

So C defines various terms, but how does it define them? In the Standard,
which is an English-language document. So sometimes C will also define the
words used to define these terms.
See the problem?
Ultimately we have to use terms like "read-only memory", which are not
defined by the C standard, but which have meanings given to them by usage.

If the OP doesn't understand why an attempt to modify a string literal
causes a crash, then its unlikely that he will be familiar with the term
"string literal". He may also be shaky on "undefined behaviour". So a
technically more accurate explanation is in fact more confusing.


I agree 100%
Furthermore, strdup() may not be specified in the Standard, it is defined by
POSIX and is widely available on the systems used by beginners. Its semantics
are easy to understand.
On the contrary, strtok() has always been part of the Standard, but is a
constant cause of misunderstandin gs and implementation bugs. IMHO programmers
should be instructed to not use this bastard, not its friends (gets, strncpy,
strncat...)

strtok modifies the string pointed to by its first argument (if not NULL) and
keeps a copy to it in a global variable.
passing it a string literal such as "this is a string" may cause undefined
behaviour, such as crash.
passing it a pointer to automatic storage, such as what you do in the example,
is error prone.
initializing a automatic character array with a string literal is inefficient.
strtok() is flawed is ways beyond the understanding of newbie developpers, it
should not be used.

Chqrlie.

Nov 14 '05 #23
"Endymion Ponsonby-Withermoor III"
<m_a_r_v_i_n@pa ra----and----.want-to-do.coe.ukk> wrote in message
news:cm******** **@newsg4.svr.p ol.co.uk...

"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:vk******** ****@brenda.fla sh-

The C standard says it is not const. The reason you should not write to
it is that the C standard says that writing to a string literal invokes
undefined behaviour.


OK. I sit corrected.


you pedants are so picky and righteous !

The C standard did not make it const char to avoid breaking countless sloppy
programs with compile time errors...
And more often than not, inconsistent use of char and string literals, hiding
subtile bugs waiting to bite at runtime.
So it is not "const", but if you try to modify it, you get UB ! Its has the
flavor and behaviour, but not the type...
Gimme a break, I'd rather newbies think it *be* const are understand why they
get a crash.

The case of the missing return statement is even a worse hack to accomodate
historical trash. It is about time some of those remnents from the 70s should
be fixed.

Just exactly what prevented the inclusion of strdup() into the Standard eludes
me !

The case against strtok() is also worth fighting : please stop teaching newbies
to use functions with flawed semantics like this one or its friends : gets(),
strncpy(), strncat()...

Chqrlie.

Nov 14 '05 #24
"Charlie Gordon" <ne**@chqrlie.o rg> wrote:
you pedants are so picky and righteous !
With good reason.
Just exactly what prevented the inclusion of strdup() into the Standard eludes
me !
It's easily emulated and would sit awkwardly in whichever header you put
it in.
The case against strtok() is also worth fighting :
strtok() has its problems, but where it's useful, it's very useful.
please stop teaching newbies to use functions with flawed semantics like
this one or its friends : gets(), strncpy(), strncat()...


Obviously I agree about gets(), and strncpy() is rarely if ever the
right function, but if you won't allow strncat(), which function _do_
you use when you want a length-limited string copy?

Richard
Nov 14 '05 #25
Hello,
The case against strtok() is also worth fighting :


strtok() has its problems, but where it's useful, it's very useful.
please stop teaching newbies to use functions with flawed semantics like
this one or its friends : gets(), strncpy(), strncat()...


Obviously I agree about gets(), and strncpy() is rarely if ever the
right function, but if you won't allow strncat(), which function _do_
you use when you want a length-limited string copy?


Why not write one that does what is needed.

Or use a test and write appropriate code for each case.

strncat() is not the worst of these, but it is consistently misused in code I
come across :

strncpy(dest, source, sizeof(dest)); // dangerous !
strncat(dest, source, sizeof(dest)); // worse even!

Chqrlie.

PS: the glove don't fit, you must acquit !
Nov 14 '05 #26
On Tue, 16 Nov 2004 12:36:55 +0100, Charlie Gordon wrote:

....
The case against strtok() is also worth fighting : please stop teaching newbies
to use functions with flawed semantics like this one or its friends : gets(),
strncpy(), strncat()...


What's wrong with strncat()?

Lawrence

Nov 14 '05 #27
"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******** *************** *****@netactive .co.uk...
On Tue, 16 Nov 2004 12:36:55 +0100, Charlie Gordon wrote:

...
The case against strtok() is also worth fighting : please stop teaching newbies to use functions with flawed semantics like this one or its friends : gets(), strncpy(), strncat()...


What's wrong with strncat()?


It is often misunderstood, and misused :

strncpy(dest, source, sizeof(dest)); // dangerous !
strncat(dest, source, sizeof(dest)); // worse even!

Chqrlie.
Nov 14 '05 #28


Lawrence Kirby wrote:
On Tue, 16 Nov 2004 12:36:55 +0100, Charlie Gordon wrote:

...

The case against strtok() is also worth fighting : please stop teaching newbies
to use functions with flawed semantics like this one or its friends : gets(),
strncpy(), strncat()...


What's wrong with strncat()?


He probably refers to Criminally Stupid Behaviour (TM), such as
ignoring the difference between the size of the destination
and the number of characters that still fit in, that is using
strncat(dst, src, dst_size);
instead of
strncat(dst, src, dst_size-strlen(dst)-1);
However, if you have to work with people who cannot or do not
want to read and comprehend the function documentation, this is
really just one of the many things which will go wrong.

I guess that he would rather like to pass the overall size of the
destination which is IMO no bad idea at all.
The only question to answer is then whether to make the last
character '\0' if no string terminator was encountered or not.
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #29


Michael Mair wrote:


Lawrence Kirby wrote:
On Tue, 16 Nov 2004 12:36:55 +0100, Charlie Gordon wrote:

...

The case against strtok() is also worth fighting : please stop
teaching newbies
to use functions with flawed semantics like this one or its friends :
gets(),
strncpy(), strncat()...

What's wrong with strncat()?

He probably refers to Criminally Stupid Behaviour (TM), such as
ignoring the difference between the size of the destination
and the number of characters that still fit in, that is using
strncat(dst, src, dst_size);
instead of
strncat(dst, src, dst_size-strlen(dst)-1);
However, if you have to work with people who cannot or do not
want to read and comprehend the function documentation, this is
really just one of the many things which will go wrong.

I guess that he would rather like to pass the overall size of the
destination which is IMO no bad idea at all.
The only question to answer is then whether to make the last
character '\0' if no string terminator was encountered or not.

Misleading: I mean in the destination (that is
strlen(dst)>= the passed size)


Cheers
Michael

--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #30

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

Similar topics

0
1670
by: Tom Schmitt | last post by:
Hi everybody. For a long time now, I've been searching for a good, fast, reliable CMS. Most of the stuff out there (like phpnuke) is too fancy and overloaded for what I need: - more than one Menu-Layer... submenus and all - MySQL-support - configurable templates - custom input templates (not a must) That's all I need. Do you have any suggestions on what to use/try out?
7
3383
by: Oliver Andrich | last post by:
Hi everybody, I have to write a little skript, that reads some nasty xml formated files. "Nasty xml formated" means, we have a xml like syntax, no dtd, use html entities without declaration and so on. A task as I like it. My task looks like that... 1. read the data from the file. 2. get rid of the html entities 3. parse the stuff to extract the content of two tags.
11
3352
by: doltharz | last post by:
Please Help me i'm doing something i though was to be REALLY EASY but it drives me crazy The complete code is at the end of the email (i mean newsgroup article), i always use Option Explicit and Response.Expires=-1,
4
1800
by: Teknowbabble | last post by:
Hi All... Ive done several simple web pages, no biggy! Is there any way to layout a Table with lets say 3 columns and have the contents of those columns not have to fit the rigid row column standard of setting up tables. Basically all I want to do is fill up column one, then column 2, and then column 3. Each column has its spacing.
38
4597
by: Kai Jaeger | last post by:
I am playing with setting font sizes in CSS using em as unit of measurement. All seems to be fine. Even Netscape Navigator shows the characters very similar to IE, what is not the kind if px is used! But! when selecting the "Larger" or "Smaller" command from the menubar in IE, font sizes increases from normal (1em) to, say, 6em or so _in the first step_!!! In the next step it seems to be 20em or say. Choosing "Smaller" makes the text...
9
2341
by: rbronson1976 | last post by:
Hello all, I have a very strange situation -- I have a page that validates (using http://validator.w3.org/) as "XHTML 1.0 Strict" just fine. This page uses this DOCTYPE: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> When I change the DOCTYPE to (what should be the equivalent):
1
4600
by: Bruce W.1 | last post by:
I want to put a live connection in a web page to periodically updated data. When the data changes, the server notifys the client and gives the new data. The client does not regularly refresh the page. The client responds to server-side events only. The screen display changes without any user interaction. An application like this might be a chat, stock ticker, or data inventory. Sofar as I can tell nothing in the .NET framework can...
5
1715
by: Pupeno | last post by:
Hello, I am experiencing a weird behavior that is driving me crazy. I have module called Sensors containing, among other things: class Manager: def getStatus(self): print "getStatus(self=%s)" % self return {"a": "b", "c": "d"} and then I have another module called SensorSingleton that emulates the
3
1771
by: squash | last post by:
I have spent two hours trying to make sense of this script, called crazy.php. The output should be nothing because $cookie_password is nowhere defined in this script, correct? But it actually outputs the value that other scripts i have running set it to. Why should crazy.php care what other scripts are running that use that variable name?? <?php crazy();
2
3631
by: kheitmann | last post by:
OK, so I have a blog. I downloaded the "theme" from somewhere and have edited a few areas to suit my needs. There are different font themes within the page theme. Long story short, my "Text Posts" are supposed to be in the font: Georgia, but they are showing up in "Times New Roman"...blah! I can't find anything wrong in the code, but who am I trying to fool? I know nothing about this stuff. The code is below. The parts that I *think*...
0
9672
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
9519
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
10214
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
10164
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,...
1
7540
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
6780
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
5437
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
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.