Re: Way around error?
From: Joseph M. Newcomer (newcomer_at_flounder.com)
Date: 05/04/04
- Next message: Joseph M. Newcomer: "Re: Focus problem when using UI thread"
- Previous message: Joseph M. Newcomer: "Re: Tools for building forms in VC6"
- In reply to: Balboos: "Way around error?"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 03 May 2004 22:13:27 -0400
See below....
On Mon, 03 May 2004 03:33:36 GMT, Balboos <balboos@masonicbrother.com.No.Spam> wrote:
>Hi, all.
>
>I'm making a number of function overloads for a 'capitlizing' function,
>it's purpose to convert an input string to mixed upper and lower case as
>though it were (for example) a name. The (char *) version's giving me
>some grief. The code (below) works if the string is allocated from the
>heap, but not from the stack (access violation).
>
>i.e., if I use:
>char instring[9] = "john doe";
>I get back "John Doe".
*****
That is because this creates an array on the stack, in writeable storage, no problem
****
>
>If I use
>char *instring = "john doe";
****
You have created a reference to constant storage, which is write-protected. So the access
failure is not at all surprising. It in fact would indicate a deep error in the system if
it did NOT give you an access fault.
Answer: don't pass constant strings to something that wants a non-constant value. I
consider it a deep error in the compiler that you don't get a warning that you have
attempted to convert a const value to a non-const pointer.
*****
>I get the access violation at the first attempt to modify the string.
>Similarly, if I call the function with the text as the argument.
>i.e., Capitalize("john doe"), it crashes.
>
>// SOURCE
>char *Capitalize(char *instring) {
>
>char *tmp; // for copy of pointer to input char string.
>bool needUC=true; // set if we 'need' to make next alpha UC; else LC
>
> if(instring!=NULL) {
> strlwr(instring); // Start out all LC - ACCESS VIOLATION!
> for(tmp=instring; *tmp; ++tmp) {
> if(!isalpha(*tmp)) {
> needUC = true; // We've hit a non-alpha - set UC flag
> continue;
> } // if(!isalpha(*tmp))
> if(needUC) {
> *tmp = toupper(*tmp);
> needUC = false; // set flag that UC is satisfied
> } // if(needUC)
> } // while(tmp=instring; *tmp; ++tmp)
> } // if(instring!=NULL)
>
>return instring;
>} // char *Capitalize(char *instring)
>
>Is there a way around this?
>
>Balboos
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
- Next message: Joseph M. Newcomer: "Re: Focus problem when using UI thread"
- Previous message: Joseph M. Newcomer: "Re: Tools for building forms in VC6"
- In reply to: Balboos: "Way around error?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|