473,944 Members | 1,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read-only string

why the following string, 'str' is read-only?

char *str = "test string";

anyhow 'str' needs to be in memory. do you think, making 'str' red-only
would gain performance? or, it is right?

Jun 21 '06
24 2730

v4vijayakumar wrote:
Vladimir Oka wrote:
v4vijayakumar wrote:
why the following string, 'str' is read-only?

char *str = "test string";

anyhow 'str' needs to be in memory. do you think, making 'str' red-only
would gain performance? or, it is right?
Character pointer `str` is /not/ read-only. You are free to assign any
other character pointer value to it. What /is/ read-only is the string
literal somewhere in memory to which `str` points.

One reason for this is that it enables embedded applications to put the
string literal into (physically) read-only memory. This may or may not
gain performance, but certainly saves RAM which in these systems tends
to command a price premium.

saving RAM?!


RAM in your mobile phone ("cell" if you're on the other side of the
pond), to give one example, can command a price premium compared to
other types of memory used in it (mainly Flash). Being generally
faster, it can also be better used for time critical task (reading
constant strings is rarely such a task).

The fact that PC RAM and HDD space is (comapratively) cheap these days
is irrelevant to that particular market segment. Don't be blinded by
the obvious.
anyhow still, you have to have these 12 bytes in RAM.


Why, if you care to explain?

Yes, if you want to modify them, but then you're going about it the
wrong way. At least in C.

Jun 21 '06 #11

v4vijayakumar wrote:
Marc Boyer wrote:
Le 21-06-2006, v4vijayakumar <v4***********@ yahoo.com> a écrit :
why the following string, 'str' is read-only?

char *str = "test string";


Because that is the way the langage is defined ?
You could wonder why the langage is designed this way.
I was not there, but my few knoledges in compilation let
me assume that, for some compiler, it was easier to do
so (it allow to store it in read-only memory).

Marc Boyer

shouldn't it be the other way? it should be easier to programmers.


But it is! It makes it easy for me to create cost/performance efficient
designs.

It also makes it easy for you, if you care to study language enough to
come across use of character arrays:

char str[] = "hello, world";

Jun 21 '06 #12
v4vijayakumar wrote:

Vladimir Oka wrote:
v4vijayakumar wrote:
why the following string, 'str' is read-only?

char *str = "test string";

anyhow 'str' needs to be in memory. do you think, making 'str' red-only
would gain performance? or, it is right?

Character pointer `str` is /not/ read-only. You are free to assign any
other character pointer value to it. What /is/ read-only is the string
literal somewhere in memory to which `str` points.

One reason for this is that it enables embedded applications to put the
string literal into (physically) read-only memory. This may or may not
gain performance, but certainly saves RAM which in these systems tends
to command a price premium.

saving RAM?! anyhow still, you have to have these 12 bytes in RAM.


Imagine an application with a lot of strings (my linux shell /bin/bash
seems to have almost 50KiB of text!).
Placing these strings in a read only "segment" can allow OSs to share
that part among multiple running instances of the application.
And it allows merging of strings too, ("World" and "Hello World" might
need just a 12 bytes of storage for those 2 strings + the pointers to
them) save a bit here and there , it might add up.

Jun 21 '06 #13
Vladimir Oka wrote:

v4vijayakumar wrote:

[...]
> char *str = "test string";
[...] shouldn't it be the other way? it should be easier to programmers.


But it is! It makes it easy for me to create cost/performance efficient
designs.

It also makes it easy for you, if you care to study language enough to
come across use of character arrays:

char str[] = "hello, world";


And things like this can lay in hiding in a program for years, or
even decades. Literally!

I had written code, back in the early 1980's, which included the
equivalent of:

char *filename = "foo.xxx";

...

strcpy(filename +4,"bar");

This "worked" until sometime in the 1990's, when the program was
ported to a system which actually did place "foo.xxx" into a read-
only memory segment. (Note that it was still in RAM. It's just
that the hardware and O/S supported marking some pages of memory
as "read-only data".)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Jun 21 '06 #14
"Nils O. Selåsdal" wrote:
[...]
And it allows merging of strings too, ("World" and "Hello World" might
need just a 12 bytes of storage for those 2 strings + the pointers to
them) save a bit here and there , it might add up.


I assume that it could also merge "Hello" and "Hello World", _if_ the
"Hello" were defined without the trailing nul?

Now, how does one define a pointer to 5 chars?

cdecl says:

cdecl> explain char (*foo)[5];
declare foo as pointer to array 5 of char

but gcc complaint on this:

char (*foo)[5] = "Hello";

with:

foo.c:1: warning: initialization from incompatible pointer type

At first, I thought that's because "Hello" is actually an array of 6
chars, but changing it to "1234" gives the same error.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Jun 21 '06 #15
Kenneth Brody said:
"Nils O. Selåsdal" wrote:
[...]
And it allows merging of strings too, ("World" and "Hello World" might
need just a 12 bytes of storage for those 2 strings + the pointers to
them) save a bit here and there , it might add up.
I assume that it could also merge "Hello" and "Hello World", _if_ the
"Hello" were defined without the trailing nul?

Now, how does one define a pointer to 5 chars?

cdecl says:

cdecl> explain char (*foo)[5];
declare foo as pointer to array 5 of char


Yes.

but gcc complaint on this:

char (*foo)[5] = "Hello";


Yes, because char (*)[5] is not the same as char * (which is what you get
when you evaluate a char[6] such as "Hello").

This works, though:

char bar[5] = "Hello"; /* caveat - bar does not contain a string */
char (*foo)[5] = &bar;
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 21 '06 #16
On 2006-06-21, v4vijayakumar <v4***********@ yahoo.com> wrote:
why the following string, 'str' is read-only?

char *str = "test string";

anyhow 'str' needs to be in memory. do you think, making 'str' red-only
would gain performance? or, it is right?


Well, being as the compiler is allowed to put "test string" wherever it
wants, it could elect to put it within the executable code.

Now, an OS will likely not allow programs to modify executable code,
because that will make it too easy to create viruses. Therefore,
strings store in executable code are not modifiable.
That should be enough of an example for you; for others, read the rest
of the thread.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 21 '06 #17
"v4vijayaku mar" <v4***********@ yahoo.com> writes:
Marc Boyer wrote:
Le 21-06-2006, v4vijayakumar <v4***********@ yahoo.com> a écrit :
> why the following string, 'str' is read-only?
>
> char *str = "test string";


Because that is the way the langage is defined ?
You could wonder why the langage is designed this way.
I was not there, but my few knoledges in compilation let
me assume that, for some compiler, it was easier to do
so (it allow to store it in read-only memory).


shouldn't it be the other way? it should be easier to programmers.


Easier to do what?

If strings are writable, then this program:
=============== =============== ==========
#include <stdio.h>
#include <string.h>

static void print_string(ch ar *s)
{
puts(s);
strcpy(s, "xxxxx");
}

int main(void)
{
int i;
for (i = 0; i < 2; i ++) {
print_string("H ello");
}
return 0;
}
=============== =============== ==========
will produce this output:
=============== =============== ==========
Hello
xxxxx
=============== =============== ==========

It's easy enough to do this if it's what you want. By preventing you
from modifying string literals, the implementation is, in a small way,
preventing you from shooting yourself in the foot.

--
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.
Jun 21 '06 #18
>Kenneth Brody said:
... but gcc complaint on this:
char (*foo)[5] = "Hello";

In article <jN************ ********@bt.com >
Richard Heathfield <in*****@invali d.invalid> wrote:Yes, because char (*)[5] is not the same as char * (which is what you get
when you evaluate a char[6] such as "Hello").

This works, though:

char bar[5] = "Hello"; /* caveat - bar does not contain a string */
char (*foo)[5] = &bar;


Note that you can also write:

char (*p0)[5] = &"1234";

If you want a non-string, you must either use the method Richard
Heathfield showed above, or the newfangled C99 compound-literals:

char (*p1)[5] = &(char []){'H', 'e', 'l', 'l', 'o'};
char (*p2)[5] = &(char [5]){"Hello"};

The size of the array can be omitted only in the initializer for
p1, in this case.

(Sure would be nice if C89 had allowed one to write "Hello\z"
to suppress the trailing \0, instead of making up a silly rule for
array initializers with specified sizes. :-) )
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jun 21 '06 #19
On 21 Jun 2006 04:09:23 -0700, in comp.lang.c , "v4vijayaku mar"
<v4***********@ yahoo.com> wrote:
(of readonly data)
saving RAM?! anyhow still, you have to have these 12 bytes in RAM.


No, you could burn it into ROM or an EEPROM or whatever. This is in
fact what many embedded systems do. Consider the BIOS in your
computer.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jun 21 '06 #20

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

Similar topics

2
9023
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 machine, but I have not found any
6
3486
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 read loop. I have: (this is a simplified version; I know there's no detailed error
12
11698
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 <iomanip> #include <fstream> #include <iostream>
2
3106
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 current user) that tells me when the user last read items in the aggregated database.
2
2516
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
3856
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
4014
by: Jose Reckoner | last post by:
I'm running python 2.3 on Windows XP. Anyone have a quick small script to convert .DT1 and .DEM data to ASCII or some other format? I don't need a viewer. Thanks!
0
4780
by: phplasma | last post by:
Hey, I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express. I have successfully made the client application establish a connection, and send data, which appears in plain, de-crypted text on the server - this works.
4
2830
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
5
12891
by: Thomas Christensen | last post by:
This issue has been raised a couple of times I am sure. But I have yet to find a satisfying answer. I am reading from a subprocess and this subprocess sometimes hang, in which case a call to read() call will block indefinite, keeping me from killing it. The folloing sample code illustrates the problem: proc = subprocess.Popen(,
0
10148
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11548
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11140
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11317
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
8239
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6315
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4927
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
2
4519
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3523
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.