473,566 Members | 3,273 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read-only functionality without 'const'

Hi,

While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory
and the string 'hello' in second method lie in a modifiable memory ?
Only 'const' provides the 'Read-only' functionality in C . How come
this "char *s" provides that functionality ? What is the internal of
this functionality actually ?

The following is the snapshot of the info that has prompted me to
raise this query :-
In any context, char *s = "Hello"; just means that the pointer s is
assigned the address of the string literal "Hello". Normally, that
string literal will reside in read-only memory which means that it's
not legal to do:
char *s = "Hello"; s[1] = 'a';

while it's perfectly legal to do
char s[] = "Hello"; s[1] = 'a';

Thx in advans,
Karthik Balaguru

Aug 16 '07 #1
26 2093
karthikbalaguru <ka************ ***@gmail.comwr ote:
While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory
Who says it does? It _may_, because it's a string literal, and string
literals are allowed to be non-modifiable. To be exact, modifying the
contents of the array that is created to hold the string literal has
undefined behaviour, which means that anything may happen, from the
modification succeeding, through it being ignored, crashing the program,
and if the implementation is being intentionally malevolent, anything up
to sending lurid emails in your name to CERT-In.
and the string 'hello' in second method lie in a modifiable memory ?
Because it's a normal object, which is initialised from a string
literal; but once initialised, it is a normal, modifiable array object.
Only 'const' provides the 'Read-only' functionality in C .
Wrong.
How come this "char *s" provides that functionality ?
It doesn't; the fact that it points at a string literal does. Had you
pointed the pointer at a char array _object_ rather than at a string
literal, you could have modified it.
What is the internal of this functionality actually ?
That sentence no meaning.

Richard
Aug 16 '07 #2
karthikbalaguru wrote:
While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory
It /may/ lie in read-only memory. It's not /required/ to.
and the string 'hello' in second method lie in a modifiable memory ?
The standard says it's undefined behaviour to write into a string
literal. So an implementation can put string literals in read-only
memory because, if anyone writes into them, the standard says All
Bets Are Off.
Only 'const' provides the 'Read-only' functionality in C .
Not really true.
How come this "char *s" provides that functionality ?
It doesn't. It's not to do with `char *` ness. It's to do with
"Hello" being a string literal. You're not allowed to modify
the contents thereof.

In the second initialisation `char s[] = "Hello";`, the /content/
of that literal is copied into the store allocated for `s`. (And
that content doesn't change, since if you tried, you'd get UB.)
Since you don't get access to the insides of the literal, whether
or not it happened to be read-only doesn't matter. Indeed, the
implementation might not need to keep the literal around at all.

[It might, as an implementation-specific example, implement

char s[] = "f";

inside a function as

mov r0, #'f'
str r0, [fp], #offsetOf(s)

so that the content of the literal string ends up encoded in
the immediate value of the `ldr` instruction.]

--
Chris "the long arm of the lore" Dollin

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

Aug 16 '07 #3
karthikbalaguru wrote:
>
Hi,

While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory
What should the following code do?

char *s = "Hello";

*s = '\0';
puts("Hello");

Even if the meaning of that code wasn't explicitly
made undefined by the C standard,
it is obviously ambiguous code.

--
pete
Aug 16 '07 #4
>
Only 'const' provides the 'Read-only' functionality in C .

Not really true.
Sorry, i should have used that in a clear fashion.
For true compile-time constant , we need to use '#define' or perhaps
'enum'.
For run time constants, we need to use 'const' telling that it can not
be manipulated/changed.
I think, the above is true now.
Is there something else that makes it false ?

Aug 16 '07 #5
karthikbalaguru wrote:
Only 'const' provides the 'Read-only' functionality in C .

Not really true.

Sorry, i should have used that in a clear fashion.
For true compile-time constant , we need to use '#define' or perhaps
'enum'.
For run time constants, we need to use 'const' telling that it can not
be manipulated/changed.
I think, the above is true now.
Is there something else that makes it false ?
String literals are effectively read-only. Hence, it is not true that
Only 'const' provides the 'Read-only' functionality in C .
--
Chris "can listen as well as read, eg, Hatfield And The North." Dollin

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

Aug 16 '07 #6
pete <pf*****@mindsp ring.comwrites:
karthikbalaguru wrote:
>>
Hi,

While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory

What should the following code do?

char *s = "Hello";

*s = '\0';
puts("Hello");

Even if the meaning of that code wasn't explicitly
made undefined by the C standard,
it is obviously ambiguous code.
I don't think it is obvious at all.

Aug 16 '07 #7
Richard <rg****@gmail.c omwrote:
pete <pf*****@mindsp ring.comwrites:
karthikbalaguru wrote:
While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory
What should the following code do?

char *s = "Hello";

*s = '\0';
puts("Hello");

Even if the meaning of that code wasn't explicitly
made undefined by the C standard,
it is obviously ambiguous code.
I don't think it is obvious at all.
I guess Pete meant (but didn't explicitly wrote so) that the compiler
is free to use the same memory location for string literals whereever
they appear. In this case the "Hello" from the initialization of the
pointer could be at the same address as the "Hello" used as the argu-
ment to puts(). So if one managed to change the memory where "Hello"
resides then what puts() prints out is dependent on if the compiler
did this space-optimization or not.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Aug 16 '07 #8
jt@toerring.de (Jens Thoms Toerring) writes:
Richard <rg****@gmail.c omwrote:
>pete <pf*****@mindsp ring.comwrites:
karthikbalaguru wrote:
While trying to understand the difference between the following 2
methods, i have some interesting queries.
Method 1) char *s = "Hello";
and
Method 2) char s[] = "Hello";

How does the string 'hello' in first method lie in read-only memory

What should the following code do?

char *s = "Hello";

*s = '\0';
puts("Hello");

Even if the meaning of that code wasn't explicitly
made undefined by the C standard,
it is obviously ambiguous code.
>I don't think it is obvious at all.

I guess Pete meant (but didn't explicitly wrote so) that the compiler
is free to use the same memory location for string literals whereever
they appear. In this case the "Hello" from the initialization of the
pointer could be at the same address as the "Hello" used as the argu-
ment to puts(). So if one managed to change the memory where "Hello"
resides then what puts() prints out is dependent on if the compiler
did this space-optimization or not.
No, I know how it works (or could work). I am just saying that it is not
obvious for a new C programmer.
>
Regards, Jens
--
Aug 16 '07 #9
karthikbalaguru <ka************ ***@gmail.comwr ites:
Only 'const' provides the 'Read-only' functionality in C .

Not really true.

Sorry, i should have used that in a clear fashion.
For true compile-time constant , we need to use '#define' or perhaps
'enum'.
For run time constants, we need to use 'const' telling that it can not
be manipulated/changed.
I think, the above is true now.
Is there something else that makes it false ?
Remember that "const" doesn't really mean "constant"; it merely means
"read-only". For example, 42 is a constant, but:
const int x = 42;
x is not a constant; it's merely read-only. (But the compiler can
choose to store x in read-only memory, or not store it at all if its
address is never used; nevertheless, x can't be used where a constant
expression is required.)

Attempting to *directly* modify something declared as "const" is
illegal (a constraint violation, requiring a diagnostic):
x = 43; /* ILLEGAL */

If you attempt to *indirectly* modify something declared as "const",
the compiler isn't required to complain, but the behavior is
undefined:
int *ptr = (int*)&x; /* the cast discards the "const"; bad idea */
*ptr = 43; /* UNDEFINED BEHAVIOR */

A string literal is not "const" (for historical reasons) but any
attempt to modify the contents of a string literal also invokes
undefined behavior. This isn't because it's const (it isn't); it's
because the standard explicitly says that it's undefined behavior.
The language would be a bit cleaner if string literals actually were
"const", but that would have broken old code written before "const"
was introduced to the language.

If you write:
char *s = "hello"; /* DANGEROUS */
you're treading on dangerous ground. The initialization is legal,
because the string literal isn't const, but it means that the compiler
isn't required to complain if you try to modify *s or s[0]. Doing so
might happen to work, or it might blow up in your face. To be safe,
*pretend* that string literals are really const:
const char *s = "hello"; /* BETTER */

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 16 '07 #10

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

Similar topics

2
8981
by: Gunnar | last post by:
Hello, I've just written a CPP program that reads integers from a binary file, and used this code while (my_ifstram.read( (char* ) &number, sizeof(int)) { // do something with number } My question is now, where can I find a manual that describes what the read method does with the ifstream object? I'm sitting here with my Linux/Debian...
6
3444
by: Steve | last post by:
Hi, I'm trying to convert a file reading loop into one using streams. The BSD OS read API returns the number of bytes read, but istream::read returns itself. How can I find out the number of bytes actually read? What the code fragment should do is read up to 1000 bytes into a buffer, or finish early if reading failed. Just your average...
0
1865
by: munif | last post by:
i wnat write a C++ program that would read from a CD and display information about files and folders in the given CD In simple words you would be performing a simple (ls -l) or (DIR /S) on the CD. LOOk at this code /*
12
11636
by: Steven T. Hatton | last post by:
I know of a least one person who believes std::ifstream::read() and std::ofstream::write() are "mistakes". They seem to do the job I want done. What's wrong with them. This is the code I currently have as a test for using std::ifstream::read(). Is there anything wrong with the way I'm getting the file? #include <vector> #include...
2
3071
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing this by aggregating new content from all databases into a single indexed database and then saving a timestamp in the account database (for the...
2
2498
by: Andrea Bauer | last post by:
Hallo, wie kann ich so eine Datei unter .Net schreiben C++ oder C#. Bitte mit Funktionsaufrufen. Vielen Dank. Grüße Andrea <Product> <ProgramNumber>2</ProgramNumber>
4
3837
by: Ollie Cook | last post by:
Hi, I am having some difficulty with read(2) and interrupting signals. I expect I am misunderstanding how the two work together, so would appreciate some guidance. I am trying to 'time out' a socket read after a certain delay. The logic is (I will provide a test program below): - create and connect socket
1
5770
by: Arpan | last post by:
The contents of a text file are as follows: The Quick Brown Fox Jumped Over The Lazy Dog. Note that there isn't any space at the end of each of the 3 lines. Now when I do this:
7
2131
by: Tracks | last post by:
I have old legacy code from vb5 where data was written to a file with a variant declaration (this was actually a coding error?)... in vb5 the code was: Dim thisdata as integer Dim thatdata Dim someother as integer thatdata = ubound( Array1 )
4
2779
by: zl2k | last post by:
hi, there I have a appendable binary file of complex data structure named data.bin created by myself. It is written in the following format: number of Data, Data array Suppose I have following data.bin (3 Data appended to 2 Data): 2, data0, data1, 3, data0, data1, data2
0
7673
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...
0
7584
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...
0
7893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8109
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...
1
7645
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...
0
5213
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...
0
3643
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...
1
2085
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1202
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.