EASY ONE GUYS/GALS: const pointers----->>>>>>

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Chris P. Randl » Wed, 22 May 1996 04:00:00



When I compile this code, I get a segmentation fault on my UNIX box:

char* p = "Hi";
*p = 'p';

Is the reason because "Hi" is a constant literal?
(Someone compiled this with a C compiler and there were no errors)
Thanks GUYS/GALS!


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Steve Clama » Thu, 23 May 1996 04:00:00




Quote:>When I compile this code, I get a segmentation fault on my UNIX box:

>char* p = "Hi";
>*p = 'p';

>Is the reason because "Hi" is a constant literal?

It is because "Hi" is a literal. Whether it is constant is up to the
implementation. The results of your assignment above are undefined in
both C and C++. Evidently the C and C++ implementations you tried made
different choices.

---


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by David Kastr » Thu, 23 May 1996 04:00:00



   When I compile this code, I get a segmentation fault on my UNIX box:

   char* p = "Hi";
   *p = 'p';

   Is the reason because "Hi" is a constant literal?
   (Someone compiled this with a C compiler and there were no errors)
   Thanks GUYS/GALS!

Right. This is the reason that, for a while, strings were of type
const char *. This has been changed (I believe) since too many error
messages ensued because lazy people were not using const char *
pointers whenever they did not need to change anything (underuse of
constness is still a very popular programming mistake. I say mistake,
because it omits vital optimization information to the compiler).

In C++, basically, the behaviour is undefined, if I am not mistaken.

- --
David Kastrup     Institut fuer Neuroinformatik, Ruhr-Universitaet Bochum


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Mark Adelsberg » Thu, 23 May 1996 04:00:00



Quote:> char* p = "Hi";

This line creates a character pointer, creates a temporary character array
somewhere in memory (in which it stores {'H','i','\0'}), points p to that
temporary array, then releases the temporary array as the compiler no longer
thinks it is needed.  So, p now points to some arbitrary location in memory
which, depending on how your system manages memory, may not belong to your
program anymore and certainly has undefined contents in the context of your
program.

Quote:> *p = 'p';

This one tries to write to that arbitrary location in memory I was just
talking about, and so it seg faults.

If you actually have a use for this, try something like:

char p[3] = "Hi";  //actually gives you the memory in question
*p = 'p';          //not the best form, but will work.

Actually, the second line would be better as

p[0] = 'p';

and you have to remember that you only control as much memory as the
declaration (char p[3]) requested.  Still, that works out better than
a declaraction of char *p, which doesn't actually give you any memory
for your string at all.

--
Mark Adelsberger / N0YRR

To err is human, to moo bovine.


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Poul A. Costinsk » Fri, 24 May 1996 04:00:00



> When I compile this code, I get a segmentation fault on my UNIX box:

> char* p = "Hi";
> *p = 'p';

> Is the reason because "Hi" is a constant literal?YES.
> (Someone compiled this with a C compiler and there were no errors)

In C it's not constant!
Generally, it's up to compiler whether to put literals
on code/const data segment.

--
Hope this helps.
Regards,
Poul.
  ("`-''-/").___..--''"`-._      ~~~~~~~~~~Poul A.
Costinsky~~~~~~~~~~


   _..`--'_..-_/  /--'_.' ,'
  (il).-''  (li).'  ((!.-    
http://www.wizsoft.com/~Poul/poul.htm


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Janu » Sat, 25 May 1996 04:00:00



>char p[3] = "Hi";  //actually gives you the memory in question
>*p = 'p';          //not the best form, but will work.
>Actually, the second line would be better as
>p[0] = 'p';

Sorry if I'm too tired at this hour of the wee, but is there any
*real* difference between the two ? I'll be damned if I (or BC4.5)
can find any.

Bye from
Janus at Kerry, Ireland

WWW : http://www.iol.ie/~jab


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Kevin H Blenkinsop » Sat, 25 May 1996 04:00:00




> > char* p = "Hi";

> This line creates a character pointer, creates a temporary character array
> somewhere in memory (in which it stores {'H','i','\0'}), points p to that
> temporary array, then releases the temporary array as the compiler no longer
> thinks it is needed.

absolutely untrue for most, if not all pc compilers. this memory is NOT
temporary storage, it's a piece of the executable that is usually called the
const data segment (on 16-bit compilers it usually lives at the far end of the
stack segment). unsurprisingly, it's where all the literals get stashed, and
they're always there for the life of the program.

[snip]

Quote:> If you actually have a use for this, try something like:

> char p[3] = "Hi";  //actually gives you the memory in question

which is exactly the same as char* p = "Hi", except that the compiler will
check that the literal (including the nul) is no more than 3 bytes.

Quote:> *p = 'p';          //not the best form, but will work.

> Actually, the second line would be better as

> p[0] = 'p';

since the original k&r, these two have been syntactically equivalent in c.
it's a matter of personal preference. in c++, they are not necessarily the
same (because of the potential for operator overloading)

Quote:> and you have to remember that you only control as much memory as the
> declaration (char p[3]) requested.  Still, that works out better than
> a declaraction of char *p, which doesn't actually give you any memory
> for your string at all.

_unless_ you point it at a literal.

--
Kevin.

"Kiss me where the sun don't shine,
The past was yours, but the future's mine."


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Wil Ever » Sat, 25 May 1996 04:00:00



Adelsberger) writes:

> > char* p = "Hi";

> This line creates a character pointer, creates a temporary character
> array somewhere in memory (in which it stores {'H','i','\0'}), points p
> to that temporary array, then releases the temporary array as the
> compiler no longer thinks it is needed.  So, p now points to some
> arbitrary location in memory which, depending on how your system manages
> memory, may not belong to your program anymore and certainly has
> undefined contents in the context of your program.

No.  This line initializes a character pointer with the address of the
first element of a statically allocated character array containing an 'H',
a 'i' and a '\0'. The array is allocated when the program is loaded into
memory and will stay allocated for the entire lifetime of the program.
Other occurences of the literal "Hi" or even "susHi" in the program may
share that same array.

Quote:> > *p = 'p';

> This one tries to write to that arbitrary location in memory I was just
> talking about, and so it seg faults.

If you get seg fault here, it is because the array is allocated in a memory
area that is somehow write-protected.  Compilers are allowed to do that
because writing into such an array results in undefined behaviour.
However, reading the characters in the array is a well-defined operation
that should never cause any problems.

- Wil


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by J. Kan » Sat, 25 May 1996 04:00:00





|>    When I compile this code, I get a segmentation fault on my UNIX box:

|>    char* p = "Hi";
|>    *p = 'p';

|>    Is the reason because "Hi" is a constant literal?
|>    (Someone compiled this with a C compiler and there were no errors)
|>    Thanks GUYS/GALS!

|> Right. This is the reason that, for a while, strings were of type
|> const char *.

Literal strings have never had the type "const char*" (or "const
char[]).  Literal strings *are* unmodifiable.  Any attempt to modify a
literal string results in undefined behavior.

|> This has been changed (I believe) since too many error
|> messages ensued because lazy people were not using const char *
|> pointers whenever they did not need to change anything (underuse of
|> constness is still a very popular programming mistake.

When literal strings were made unmodifiable (in the C standard), const
didn't exist (or hadn't existed before), so it is not surprising that
people didn't use it.  Believe it or not, there are still C compilers
delivered today that don't support const.

You are correct in stating that the reason a string literal doesn't have
the type "const char[]" is that it would break such code.  Given that
such code was written before const was added to the language, however, I
don't think you can accuse the programmers of laziness for not using it.


Quote:Adelsberger) writes:


|> > char* p = "Hi";

|> This line creates a character pointer, creates a temporary character array
|> somewhere in memory (in which it stores {'H','i','\0'}), points p to that
|> temporary array, then releases the temporary array as the compiler no longer
|> thinks it is needed.  So, p now points to some arbitrary location in memory
|> which, depending on how your system manages memory, may not belong to your
|> program anymore and certainly has undefined contents in the context of your
|> program.

This is completely wrong.  Literal strings have static duration: they
exist during the entire lifetime of the program.

|> > *p = 'p';

|> This one tries to write to that arbitrary location in memory I was just
|> talking about, and so it seg faults.

More likely: the compiler allocated the string in write protected memory
(since it is unmodifiable).  Writting to write protected memory will
generally cause a core dump.

|> If you actually have a use for this, try something like:

|> char p[3] = "Hi";  //actually gives you the memory in question
|> *p = 'p';          //not the best form, but will work.

Without the static, this is actually worse than the original.  This
*does* allocate memory which is released.

You might want to try:

        static char                     buffer[] = "Hi" ;
        p = buffer ;
        //  ...

This results in p pointing to a modifiable string.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils en informatique industrielle --
                            -- Beratung in industrieller Datenverarbeitung


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Jim Melto » Sat, 25 May 1996 04:00:00



> > If you actually have a use for this, try something like:

> > char p[3] = "Hi";  //actually gives you the memory in question

> which is exactly the same as char* p = "Hi", except that the compiler will
> check that the literal (including the nul) is no more than 3 bytes.

No, they are not the same (which is the genesis of the orignal post).

     char p[3] = "Hi";
allocates 3 bytes on the stack (or in the global address space,
depending on scope). This memory is read/write accessible to the
program.

     char *p = "Hi";
allocates a character pointer with the same scope as above and points it
at a literal string. Where the string is located *is* compiler
dependent, but assuming that it is writable has been broken since K&R C.
--
Jim Melton, novice guru        | As far as we know,

v-mail: (303) 714-9732         | an undetected error


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Roger Glov » Wed, 29 May 1996 04:00:00



[[ original quesition and some responses omitted - rg ]]

Quote:> > *p = 'p';          //not the best form, but will work.

> > Actually, the second line would be better as

> > p[0] = 'p';

> since the original k&r, these two have been syntactically equivalent in c.
> it's a matter of personal preference. in c++, they are not necessarily the
> same (because of the potential for operator overloading)

*Actually*, since you cannot override the operators for intrinsic
types defined by the language, the two statements above **are**
equivalent.

Nonetheless, I agree that the second is the better form in the
modified example, but for "fuzzy" stylistic reasons only.  That is, I
understand the code more easily when I avoid mixing pointer syntax
and array syntax.  So if I had defined:
    char p[3] = "Hi";
then I would have used:
    p[0] = 'p';
later.
----------------------------------------------- Roger Glover
XXXX\ \ / \ /XXX  \ / \ X   \ /\\\  X///X /\\\  Cray Research, Inc.
/ \ / \/ /\ / \ / \X /\ X  \  / \   X\  \ X     DISCLAIMER HAIKU:
//X/  X\\\X //X/  X \ X X\\   / \   X/X \ X \\\   C R I may not
/ \   X///X / \/  X//XX X  \  / \   X  \\ X   \   Share these opinions with me
/ \   X   X /\\\/ X   X X///X /XXX/ X///X /XXX/   This is not my fault
----------------------------------------------- http://home.cray.com/~glover


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

EASY ONE GUYS/GALS: const pointers----->>>>>>

Post by Kevin H Blenkinsop » Thu, 30 May 1996 04:00:00




> > > If you actually have a use for this, try something like:

> > > char p[3] = "Hi";  //actually gives you the memory in question

> > which is exactly the same as char* p = "Hi", except that the compiler will
> > check that the literal (including the nul) is no more than 3 bytes.

> No, they are not the same (which is the genesis of the orignal post).

[sound of me smacking my head on the desk]
sorry. i don't know what planet i was on at the time. i didn't actually respond
to the original post, but to something that said

| char* p = "Hi";
|
| This line creates a character pointer, creates a temporary character array
| somewhere in memory (in which it stores {'H','i','\0'}), points p to that
| temporary array, then releases the temporary array as the compiler no longer
| thinks it is needed.

which is hopelessly wrong, and then i apparently shut my brain off and went on
to disagree with the other two statements he made, one of which was right.
anyone have a copy of "c for dummies" i can borrow? or some coffee?

Quote:>      char *p = "Hi";
> allocates a character pointer with the same scope as above and points it
> at a literal string. Where the string is located *is* compiler
> dependent, but assuming that it is writable has been broken since K&R C.

which was one of the points that i made, although i've never actually used a
compiler that had problems with it - i used to change the text on help screens
to reflect the current state of toggle-able options using this. someone recently
claimed that const literals on one of the nt compilers were actually put in
non-writeable pages, but i don't know which compiler that was (apparently it's
not msvc).

--
Kevin.

"Kiss me where the sun don't shine,
The past was yours, but the future's mine."
{ Second signature elided. -mod}


      [ about comp.lang.c++.moderated. First time posters: do this! ]

 
 
 

1. Resizing a CListBox>>>>>>>>>>>>>>>>>>>>>>>>>>>

I have created a CListBox on a view...Now how can I make the listbox always
cover the entire client area of the view, even on resizing.

At the moment im overriding OnSize:-

void CMyView::OnSize(UINT nType, int cx, int cy)
{
        myListBox.MoveWindow(0,0,cx,xy,TRUE);

It doesnt do the trick. Help!!

--
================================================================================
Mr Abtar Bangar          | EMAIL ADDRESS:       |

Southbank University     |                      |  something about EVERYTHING
103 Borough Road         |                      |      but definately not    
LONDON SE1 0AA           |                      |  EVERYTHING about something'
United Kingdom.          |                      |
================================================================================

2. Apple II USer Guide forsale

3. " INNOVATION INFOS + IMAGING " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

4. ToolTip

5. HELP >>>>>>>>>>>>> WINAPI <<<<<<<<<<<<<<<<<

6. Help ! The Institute

7. Windows 3.x printqueue >>>>>>>

8. Does Visual Studio .Net FULLY support xml?

9. <<<<<<<< CREATIVE DIRECTOR NEEDED - LONDON >>>>>>>>>>>>>

10. <<<<<<Programmers Needed>>>>>>>

11. <<>><><><><><><><><><><>

12. <<<< GET A CASH GRANT >>>>>>