Archived

This topic is now archived and is closed to further replies.

strncpy crashes!

This topic is 5682 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is anything wrong with the code below and why does it crash?
  
LPSTR	lpErrMsg;
LPVOID	lpMsgBuf;

// ...

// Initializion

// ...


strncpy(lpErrMsg, reinterpret_cast<char *>(lpMsgBuf), sizeof(lpMsgBuf));
  

Share this post


Link to post
Share on other sites
1. You need to allocate memory for both both lpErrMsg and lpMsgBuf, either with new or by using an array: char lpErrMsg[100];

2. sizeof(lpMsgBuf) is always 4. That's not probably what you want. The intent of your code can be accomplished by just calling strcpy.

[edited by - IndirectX on June 27, 2002 6:47:32 PM]

Share this post


Link to post
Share on other sites
You seem to think that sizeof(lpMsgBuf) will return the length of the string lpMsgBuf points to. That is not the case. Read the manpage for strncpy, and then decide what that third argument should be.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
The length parameter to strncpy is the maximum number of characters to copy and should therefore be the size of the recieving char-array (to make sure that strncpy doesn''t write stuff in memory after the array). You don''t need to tell strncpy how long the source-string is because all strings in C and C++ are terminated by a NUL-character (ASCII 0), so strncpy can figure it out by itself.

Share this post


Link to post
Share on other sites
I isn´t working like this either:


  
LPSTR *lpErrMsg = new LPSTR;
LPVOID *lpMsgBuf = new LPVOID;
// ...// Initializion// ...

strncpy(*lpErrMsg, reinterpret_cast<char *>(lpMsgBuf), sizeof(lpMsgBuf));


Could someone give an working example and tell what´s wrong?

Share this post


Link to post
Share on other sites
<yoda>Hear you nothing that we say? </yoda>

[edited by - sneftel on June 27, 2002 7:00:32 PM]

Share this post


Link to post
Share on other sites
They did tell you enough information to solve this on you own, but since you want an example:

    
const size_t Size = 10;
char Src[] = "Fish.", *Dst;

Dst = new char[Size];

strncpy(Dst,Src,Size);

delete [] Dst;

Also, I don't think you should use Win32 typedefs (LPSTR, LPVOID) where you aren't interacting with the Win32 API. Not that it really matters, it's just not right .



[edited by - Null and Void on June 27, 2002 7:11:03 PM]

Share this post


Link to post
Share on other sites
Has NO ONE heard of strlen?

P.s. <tone sarcasm=0 type=sincere>D00d, you need to read up on how memory and dynamic allocation work. There''s a good article (that might be released on GameDev if whoever reads the mail at writers@gamedev.net gets their patooshka in gear, *hint*) titled "Understanding Pointers: A Game Developer''s Approach." I''d recommend it (ignoring the fact that I''m the author <tone>

Later,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
If you''re going to use strlen(), you wouldn''t be using strncpy() - you''d be better off using strcpy().

Thinking before posting often helps.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
If you''re going to use strlen(), you wouldn''t be using strncpy() - you''d be better off using strcpy().

Thinking before posting often helps.


I''m pretty sure ZE was talking about the code fragment allocating space for the destination string. For that matter, if you''re using strlen() for the copy-size, then you''d use memcpy, not strcpy. Take your own advice.

Share this post


Link to post
Share on other sites
I''m surprised that no has said, "Just use std::string".

/*=========================================*/
/* Chem0sh */
/* Lead Software Engineer & Tech Support */
/* http://www.eFaces.biz */
/*=========================================*/

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Sneftel
I''m pretty sure ZE was talking about the code fragment allocating space for the destination string. For that matter, if you''re using strlen() for the copy-size, then you''d use memcpy, not strcpy. Take your own advice.


If you''re going to allocate a dest buffer the size of the src string, you don''t need strncpy() to copy that string, so using strlen() there would be pointless too. (if you''re copying a part of the src string, it''s another story, but using strlen() to allocate the dest buffer is moot)

Also, If you''re using strlen() with memcpy(), you''re not going to get the null byte at the end of string like you would with strcpy() - so, no, I wouldn''t use memcpy().

I stand by my original advice, and offer it to you as well.

Share this post


Link to post
Share on other sites
I need to use LPSTR and LPVOID, here´s the code currently have:


  
LPSTR lpErrMsg[256];
LPVOID lpMsgBuf[256];

FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language

(LPTSTR) &lpMsgBuf,
0,
NULL
);

strncpy(*lpErrMsg, reinterpret_cast<char *>(lpMsgBuf), 256);


It still crashes, why? What´s wrong?

Share this post


Link to post
Share on other sites
You still don''t understand what the types you''re using mean. You NEED to read the article that ZE mentioned earlier. Really. Trust me. And ZE.

LPSTR a; // is a pointer to an array of characters.
LPSTR b[10]; // an array of pointers to arrays of characters.
char c[10]; // an array of characters (this is what you want)


Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions

Share this post


Link to post
Share on other sites
Try this :


  
char ErrMsg[256];
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language

(LPTSTR) lpMsgBuf,
0,
NULL);
strncpy(ErrMsg, reinterpret_cast<char *>(lpMsgBuf), 256);
LocalFree(lpMsgBuf); lpMsgBuf = 0;


BTW, if you''re going to copy chunks of code out of the MSDN samples it''s a good idea to make sure you understand what they''re doing first

I''d also advise that you spend some time getting familiar with the way that C deals with strings, aswell as getting used to the differences between pointers, arrays and instances - it''ll save you a lot of confusion in the future if you do a bit of groundwork now.

Share this post


Link to post
Share on other sites
The exact article that I mentioned hasn''t become available yet, but there are plenty of tutorials out there on pointers and dynamic memory that serve the same purpose. The fact is, if you don''t understand that LPSTR and char* are the same thing, you need help.

Peace,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Just use std::string! Your trying to use C++ by the "reinterpret_cast" so why don''t you use STL too? It will safe you a lot of time and trouble. If you think it is slow, wastes memory etc. (which I don''t agree with) just try using STL to write your program in half the time and then optimize the bottle necks when its wokring.

Share this post


Link to post
Share on other sites
I don''t care if I get flamed for this, but in my personal tests, the STL was vastly slower than my own implementation. If you encourage people to just start out using something simple and slow, they will still be just as ignorant of better solutions when it comes time to optimize. STL, when used effectively, may slightly reduce dev time and be easier, but it will NOT cut dev time in half, nor will it benefit you in any other way.

Later,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
quote:
Original post by ZealousElixir
I don't care if I get flamed for this, but in my personal tests, the STL was vastly slower than my own implementation.

That doesn't seem like flame-bait to me. Flamage tends to come hot (intentional pun) on the heels of zealotry and unqualified statements, but you've digressed from that general pattern by mentioning you have actually performed tests. I would be interested to hear more about the details of your tests, if you're willing to share. The generally accepted wisdom is that programmer time is expensive and CPU time is cheap (relatively speaking), so anything that saves on programmer time is a worthy pursuit. I'm certain the STL helps me save time in developing applications, and I've not had any issues in terms of performance - in many circumstances, the STL implements exactly what I would arrive at after many hours of effort. Would it be unfair to suggest you might have a poor implementation or might be using inappropriately?
quote:

If you encourage people to just start out using something simple and slow, they will still be just as ignorant of better solutions when it comes time to optimize.

I don't agree with this. I strongly believe there is enough about programming that makes it hard for the average person to grasp without going low-level (whilst learning general programming). I should point out that I don't program games (anymore), but I do program high-performance telecoms applications, and I find techniques such as Alternate Hard and Soft Layers to be very sensible.
quote:

STL, when used effectively, may slightly reduce dev time and be easier, but it will NOT cut dev time in half, nor will it benefit you in any other way.

I'm tempted to agree that it will not cut dev' time in half, but that's obviously a figure pulled out of thin air. There are many non-technical factors that are at-least as influential on dev' time as language and library choice. Amongst those are such things as culture, organisational structure and developer outlook/attitude. Of the attitudes that many have observed to be counter-productive, there is one that is pertinent to this discussion - Not Invented Here.


May the mountain shake you to the core!

[edited by - SabreMan on June 28, 2002 5:16:46 PM]

Share this post


Link to post
Share on other sites
Do your own tests. It''s obvious that something that''s designed to be general that can work with every possible case will break down because of it, even if it speeds up code creation time.

The STL is a solution to speed coding time. It is not a panacea for obvious misguidings about a language. In short: if you don''t know the language, you will not utilize anything past your current level with any sort of efficiency.

We''ve already had the argument over what "the basics" are. It''s totally subjective, and in this case the subject needs to learn more before he takes the easy way out. Refute that and I''ll stop writing rebuttals.

Later,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
quote:
Original post by ZealousElixir
Do your own tests.

My personal experience lead me to say the STL is completely acceptable in terms of performance. However, it's a shame you won't discuss the results of your tests.
quote:

It's obvious that something that's designed to be general that can work with every possible case will break down because of it, even if it speeds up code creation time.

The genericity of templates is a compile-time feature, and a well designed template class will not be any less efficient at run-time than a custom-built class.
quote:

The STL is a solution to speed coding time.

Amongst other things.
quote:

It is not a panacea for obvious misguidings about a language.

Such as?
quote:

In short: if you don't know the language, you will not utilize anything past your current level with any sort of efficiency.

That depends what it means to "know" the language.
quote:

We've already had the argument over what "the basics" are.

Yes I know we have, and I don't wish to repeat it.
quote:

It's totally subjective, and in this case the subject needs to learn more before he takes the easy way out.

I don't agree that it's subjective - I believe that it's objectively observable. However, since I've conducted no such investigations, I cannot claim to be doing anything more than hypothesising.
quote:

Refute that and I'll stop writing rebuttals.

Refute that the subject needs to learn more? I can't - we all need to learn more.


[edited by - SabreMan on June 28, 2002 6:00:42 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by ZealousElixir
I don''t care if I get flamed for this, but in my personal tests, the STL was vastly slower than my own implementation. If you encourage people to just start out using something simple and slow, they will still be just as ignorant of better solutions when it comes time to optimize.



Take std::string as an example. If you don''t use it you could use C style strings, which means you have to worry about memory allocation, buffer over-runs along with a high scope for error. If you wanted to write you own C++ class, you then have to test this to verify it works. Both of these methods takes considerably more time to do (design, implementing, testing, debugging, optimzing) than using STL.

Perhaps you might be able to gain a small improvement in speed, but is that where the bottle neck would have been in the first place? For example, I don''t reckon string manipulation is going to be the bottle neck in Doom 3. Get your program working first, then optimize if you have to (although, you should obviously optimize on an algorithmic scale first, within reason).

All that time you spend reinventing the wheel, your competitors are implementing important things. You just simply cannot be productive and meet deadlines if you insist on writing everything yourself because you think it might be faster.

You say no general solution will be fast in all cases. Why are you so obsessed with speed? It seems to me you are clouding your programming judgement by thinking about it so much. Would you not rather finish your game in a fraction of the time instead of taking significantly longer to do so with a tiny percentage speed increase? Where exactly do you draw the line anyway? Why not write everything in assembly? Speed is not the most important aspect of programming.

STL implementations are normally fully tested and you can use them in high confidence that they work, unlike something you just made yourself. I have found, for example, STLPort to be very well written and fast.

I have had a few programming jobs and if you told your company they have just payed you a good chunk of money to reimplement STL because you *think* it might go a little faster, they would not be happy.

quote:

STL, when used effectively, may slightly reduce dev time and be easier, but it will NOT cut dev time in half, nor will it benefit you in any other way.



I strongly disagree with "slightly reduce dev time". Think of all the work it takes to design, write, test, optimize and maintain code. If you can avoid this whilst incurring minimum speed costs, you should. Imagine the collective lost work time if every programmer wrote their own linked lists, vectors, strings etc. You need to stop basing everything on speed.

Share this post


Link to post
Share on other sites