Dangerous convertion?

F

Flash Gordon

On the other hand, banking is a bad analogy for a different reason. A
depositor has no right to remove any more money from a bank than the
current account balance, and interest rates give depositors an incentive
to take out no more than they actually need. In memory allocation,
here's no corresponding limit, and no corresponding incentive, to
restrain memory allocation requests. Therefore, the chance that a given
request might make the system will run out of memory can, to a rough
first approximation, be estimated by methods similar to those given above.

A better reason that you cannot use a method like the above for
estimating the likelihood of failure is because it depends on the type
of user and usage pattern. If a user regularly does video editing there
is a good chance that half to three quarters (or more) of the memory is
in use before you start on anything else. Or if the user regularly has
three VMWare images with half a gig of RAM allocated to each open and
also has to work on large word processor documents, and sometimes has to
copy from one document to another, the chance of the 100 byte allocation
failing when copying a small amount of text is much higher.

Before you even look at starting to estimate the frequency (or
probability) of a memory allocation of a given size failing you first
have to get some statistics on the likely base level of memory utilisation.

Probably an easier way of doing an estimate is to produce an
instrumented malloc which logs when malloc fails, how large the
allocation was, the name of the process etc. Then get a representative
selection of users to use that library and collect results.
 
M

mark

TBH a response 24 hours later is probably worthless to most people, the
internet is all about instant communication.

Just my 2c.
 
M

mark

OK thanks for the info Malclom.

Assuming sane naming conventions, this is safe.

BYTE * means a pointer to an aribtrary chunk of memory. LPBYTE is a synonym
for BYTE *. A CTSTR will be some sort of null-terminated non-ascii sequence
of characters. By converting you are telling the computer "treat this string
as a series of raw bytes".
That's quite a normal thing to do. You do strip away most of the
protection a higher-level construct would give you. Not all operations on
BYTEs are necessarily valid operations on CTSTRs. But that's because C is a
very low-level language, and does things like that for efficiency and
generality reasons.
 
K

Keith Thompson

mark said:
TBH a response 24 hours later is probably worthless to most people, the
internet is all about instant communication.

[top-posting corrected]

Usenet is about discussions, not instant answers to questions.
Answers you get within a few minutes of posting are also likely
to be worthless; followups over the next few hours or days can
correct errors.

Remember, you're communicating with people here.
 
N

Nobody

More seriously, I really, truly, have nothing but guesses
about what a `CString' may be, and no notion at all about the
meaning of `LPCTSTR'. I imagine they're C++-isms

They aren't. They're Microsoft-isms, widely used in C.

LPCTSTR is an alias for "const TCHAR *". "LP" means "long pointer", aka
"far pointer" (on DOS and Win16, "far" means that it contains both
a segment and offset), "C" means const, "STR" means string (i.e. multiple
characters). A "TSTR" is a string of "TCHAR", which is either "char" or
16-bit Unicode (WCHAR or wchar_t) depending upon whether the code is
compiled for "ASCII" (MS-speak for "non-Unicode") or Unicode.

All of this comes from trying to map a single API to half a dozen
different ABIs.
 
J

James Kuyper

mark said:
TBH a response 24 hours later is probably worthless to most people, the
internet is all about instant communication.

Usenet is more about world-wide communication, than about instant
communication. When you deal with people in widely disparate time zones,
most of them with actual jobs that require them to work (and sleep)
regular hours, you shouldn't expect instant communication. Most people
participating in these newsgroups don't expect it.

If instant communication is important to you, then usenet newsgroups are
not a good place for you to get it. I would recommend looking for
appropriate chat rooms, instead. I'm sorry, but I can't recommend any
particular chat rooms; usenet fits my needs quite well.
 
P

Phil Carmody

mark said:
TBH a response 24 hours later is probably worthless to most people, the
internet is all about instant communication.

Goodbye. Don't let the door hit you on the way out.

And sorry for the delay in getting that response to you, I was asleep.
Feel free to act upon it instantly though.

Phil
 
N

Nick Keighley

they are both microsoftisms. Whatever C++'s faults may be it never
drank the hungarian kool-aid

Look, I'll break it down for you.

couldn't you just explain what CString and LPCTSTR are?
I don't think you can expect us to understand why MS are
wrong if we don't know what they are trying to do.
You should never use strcpy.  Ever.  It's a bad habit to get in.
rubbish

Specially in a generic example showing how to copy from some type to
another because you know people will copy/paste it into their
applications.

My point was that leaving aside it's an incomplete program because
it's just a snippet, it shows that MSFT can't even write a damn string
copy example without doing it wrong.

BTW, the fact that it's a snippet and not a complete program is fine
IMHO.

ditto. And in the context of the page it was on it probably made
perfect sense.
 
N

Nick Keighley

While I agree blanket "never use X" statements are nonsense,
good


for
example, there are plenty of good uses for goto, strcpy is one that
just should be avoided.

just repeating it isn't going to convince me. You dodn't address
Eric's point in any substantive manner
It's the sort of bad habits that lead to other things like

- not checking parameters for validity
- not checking returns of malloc/calloc
- Not checking boundaries

Just Say No To DRUGS!

This is just rubbish (I used a stronger word the first time).
There is no connection between use of strcpy() and the above
problems.

How often does "malloc" really fail?  So I guess checking the return
is just paranoia, etc.  Sometimes not being lazy up front saves having
to go back and fix things later when it costs more to re-open the
code.

quite right. This is why I check the return value of malloc().
I also use strcpy() when appropriate. How do *you* copy
a string. (Please, Eris, he doesn't use strncpy()!)
As for never having a use for making a copy, sometimes you're
transferring it from one structure to another and you're not at a
point to know where the pointers came from [stack, heap, auto, ???] so
you can't just copy the pointer.

He didn't say he never copied. He said he thought about it first.
 
N

Nick Keighley

On a computer with 2GB of memory, an allocation of 100 bytes will have a
0.0000005 chance of being the culprit if the computer runs out of memory.

no. You can't calculate a probability like this. Something I run has a
memory
leak (I suspect). Sometimes programs complain that virtual memory is
low.
I suspect malloc or something like it has just failed. How does this
affect
your calculation?
The user might, hypothetically, tolerate his computer running out of memory
once every hour.  It follows that the computer will see 20,000,000 hours

that's 2000 years
service before any individual call to the routine fails,

I say more like 10 days on my computer.
 
N

Nick Keighley

That's the wrong way of looking at it.

As we all know by now, banks can fail. Say you've got an account at the high
street bank Boorcloys (fictitious name to avoid libel charges). You withdraw
a hundred pounds. What's the chance that your transaction will fail because
the bank has run out of money at that point?

its mathematical illieracy of this order that caused the problem in
the
first place. The assumption was that all those transactions were
indendent.
The probability of major bank failing when 100 UKP is withdrawn
under normal circumstances is effectivly zero. The problem occurs
when
things aren't normal.
 
A

Alexander Bartolich

Eric said:
Tom said:
You should never use strcpy. Ever. It's a bad habit to get in.

"Nonsense," "nonsense," and "too late."
[...] Using strcpy(), if the thing being copied is a string,
because it's the right tool for the job. In responsible hands,
anyhow.

strcpy() is safe only when you know that the length of the source
is less then the size of the destination. But if you know the length
of the source you can just as well call memcpy. So use of strcpy is
either unsafe or inefficient.
 
N

Nick Keighley

Nick Keighley said:


Although I agree with you that he's wrong, I think "rubbish" is a
touch strong.

I thought stronger terms. If he presented an argument I could
have refuted it. But he seemed to have little more than an unsupported
directive.

The advocacy of strncpy over strcpy is misguided,

at the time I wasn't aware he was doing that. I might have been ruder
if I had.
but it does at least show that the advocate has thought a little about
the problem,

yes, agreed good point
and that's good. It /also/ shows that (in this case) he
hasn't thought quite /enough/ about it.
yes


That there is a problem (with potential buffer overruns when using
strcpy) is indisputable
yes

(which won't stop some people disputing it, of course).

there's nowt so queer as folk
That strncpy solves the problem (if used carefully) is
also indisputable.

with some non-obvious messing around. I'd rather write a function
that does what (many) people think strncpy does. Or just check the
string will fit before I call strcpy().

Unfortunately (for the strncpy advocate) it raises
two further points: (a) if we accept that the programmer will be
careful anyway, strcpy is just fine; (b) whether or not we accept
that, the strncpy nurse throws out the data correctness baby with the
potential overrun bathwater, because it will silently truncate
excessively long strings.

plus nursey drops extra nuls into the bath whenever she feels like it.

That's why people end up writing their own
string management libraries (FCVO "string").

I think I'd need a stronger motivation
But I think "rubbish" is unnecessarily inflammatory.

opinions vary
 
J

James Kuyper

Alexander said:
Eric said:
Tom said:
You should never use strcpy. Ever. It's a bad habit to get in.
"Nonsense," "nonsense," and "too late."
[...] Using strcpy(), if the thing being copied is a string,
because it's the right tool for the job. In responsible hands,
anyhow.

strcpy() is safe only when you know that the length of the source
is less then the size of the destination. But if you know the length
of the source you can just as well call memcpy.

Knowing that the length of the source is less than the size of the
destination does not require knowing the length of the source. It's
entirely possible to process a string in such a way as to guarantee that
the source contains less than 25 characters, without knowing, at the end
of that process, what the actual length is. You could find out, of
course, using strlen(), but why not simply call strcpy() rather than a
combination of strlen() and memcpy()?
... So use of strcpy is
either unsafe or inefficient.

I call it inefficient to copy 1024 bytes out of a buffer, when the
string contained in that buffer happens to be only 8 bytes long.
 
A

Alexander Bartolich

James said:
Alexander said:
[...]
strcpy() is safe only when you know that the length of the source
is less then the size of the destination. But if you know the length
of the source you can just as well call memcpy.

Knowing that the length of the source is less than the size of the
destination does not require knowing the length of the source. It's
entirely possible to process a string in such a way as to guarantee that
the source contains less than 25 characters, without knowing, at the end
of that process, what the actual length is.

I can think of three cases:

1. You did once know the exact length but have lost this information.

2. You are processing the result of a function that reads only up to
specified maximum of characters but does not return the actual
length, e.g. fgets, fread, snprintf.

3. You are trusting external constraints, e.g. the size of a field in
binary input, the column type of a database query, the maximum
output length of inet_ntoa.
You could find out, of
course, using strlen(), but why not simply call strcpy() rather than a
combination of strlen() and memcpy()?

Well, if your destination buffer is a statically sized array and you
don't intend to append data to your string, have fun with strcpy. Of
course in such case it might be possible that you don't need a copy
of the string at all and can just keep the source buffer.
I call it inefficient to copy 1024 bytes out of a buffer, when the
string contained in that buffer happens to be only 8 bytes long.

Nice straw man you have there.
 
J

James Kuyper

Alexander said:
James said:
Alexander said:
[...]
strcpy() is safe only when you know that the length of the source
is less then the size of the destination. But if you know the length
of the source you can just as well call memcpy. ....
... So use of strcpy is
either unsafe or inefficient.
I call it inefficient to copy 1024 bytes out of a buffer, when the
string contained in that buffer happens to be only 8 bytes long.

Nice straw man you have there.

He's advocating that I not use strcpy() to copy a string known to be of
length < size of the destination, on the assumption that I must
therefore know how much to copy, and can therefore call memcpy(). One of
the most common situations where I would feel quite comfortable using
strcpy() is to copy a string from one buffer to another, knowing at the
time of the strcpy() call that the string will fit in either buffer,
without necessarily knowing what the actual string length is. The only
sense in which I "know the length of the source" is that I know that the
source fits in the input buffer, so the only sense in which his advice
could be applied to that situation is by copying the entire input buffer
to the output buffer, even though the actual string to be copied might
be much shorter than the size of the input buffer.

I don't see how that qualifies as a straw-man argument.
 
L

Lew Pitcher

Well, anyone who says "the internet is all about instant communications"
in a Usenet group has obviously never heard of Usenet.

Or email, even.


--
Lew Pitcher

Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------
 
R

Richard Bos

Tom St Denis said:
Look, I'll break it down for you.

You should never use strcpy. Ever. It's a bad habit to get in.

Tom, kick that bat out of your belfry.

There is no problem with strcpy() if you _know_, for whatever reason,
that your string will always fit within the destination. There are many
situations where the maximum length of a string is perfectly known, and
the example under discussion was one such.

Richard
 
R

Richard Bos

Malcolm McLean said:
As we all know by now, banks can fail. Say you've got an account at the high
street bank Boorcloys (fictitious name to avoid libel charges). You withdraw
a hundred pounds. What's the chance that your transaction will fail because
the bank has run out of money at that point?

With Boorcloys, perhaps not great. But what if you, in all innocence,
had your malloc() running on Southern Wuss instead? Or on Maggie Mae?

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top