473,402 Members | 2,064 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

assigments to string pointers with literals

I wonder if that is correct, in ANSI C:

char *mystring;

mystring = "helloworld";

or I should always proceed in this other, thougher, way:

char *mystring;

if( NULL == ( mystring = malloc( strlen( "helloworld") ) ) )
{
printf("error\n");
}
else
{
strcpy( mystring, "helloworld" );
}

Thanks!
Jun 2 '08 #1
9 1869
Banfa
9,065 Expert Mod 8TB
char *mystring;

mystring = "helloworld";
Well strictly speaking a string literal is constant (or should be treated that way, it is not necessarily constant on all platforms) so this should be
Expand|Select|Wrap|Line Numbers
  1. const char *mystring;
  2.  
  3. mystring = "helloworld";
  4.  
to preserve the constness of the data but otherwise this is acceptable.
Jun 2 '08 #2
So,

this means that:

I can safely assume that the compiler will reserve memory in the heap for mystring, for this const value?

Thanks.-
Jun 2 '08 #3
Going further,

You mean that, it is only possible if mystring is const? (i.e. its value can't be changed runtime?)
Jun 2 '08 #4
weaknessforcats
9,208 Expert Mod 8TB
I would generally proceed the tougher way. The reason is that passing pointers around a program ios one of the most dangerous things you can do especially when the compiler is in charge of deleting your data. By using malloc() and managing your own memory, you are responsible for deleting and this makes passing the pointer safer. Of course, you have to remember to delete and this brings its own set of problems.

Also, using the stack can cause problems since stack memory if often limited. Exceed it and your program crashes.
Jun 2 '08 #5
Banfa
9,065 Expert Mod 8TB
I can safely assume that the compiler will reserve memory in the heap for mystring, for this const value?
No, where the compiler reserves space for mystring is rather dependent on how and where you declare it but the 2 choices for the given declaration are on the stack, if the declaration is made inside a function or in global data (in the data segment) if you declare the variable outside the function but this would be poor technique.

The compiler will reserve memory for the string constant in the programs data segment, possibly in a constant data segment depending on the platform.
Jun 2 '08 #6
Banfa
9,065 Expert Mod 8TB
You mean that, it is only possible if mystring is const? (i.e. its value can't be changed runtime?)
No I mean if you want to change the value of mystring then you have to allocate memory from the heap for it.

However if you have no intention of changing what mystring is pointing to then you can conserve memory by declaring it const and just pointing it to the string literal. This is commonly used to conserve both ram and prom on a platform with limited amounts of either or both (particularly if the only compiler available is non optimising) with a definition
Expand|Select|Wrap|Line Numbers
  1. const char * const mystring = "Hello World";
  2.  
Allows the use of mystring where every you need the constant string "Hello World".
Jun 2 '08 #7
Banfa
9,065 Expert Mod 8TB
I would generally proceed the tougher way. The reason is that passing pointers around a program ios one of the most dangerous things you can do especially when the compiler is in charge of deleting your data. By using malloc() and managing your own memory, you are responsible for deleting and this makes passing the pointer safer. Of course, you have to remember to delete and this brings its own set of problems.

Also, using the stack can cause problems since stack memory if often limited. Exceed it and your program crashes.
Personally I disagree. In this limited example allocating from the heap does not reduce the use of the stack there is no data to delete, the string constant appears in the data segment and always will the pointer appears on the stack or in global data and always will. Pointers become (a little) safer when they are const, although it is true that many programmers skip on using the const keyword when they should.

In most applications and certainly in an application on a platform with limited resources there is a lot to be said for the adage of "keep it simple" and this means not putting in unrequired memory allocations.

Of course (as I said earlier) if the program is going to need to change the string then the string constant should be copied to ram first. Whether that is the on the stack or the heap rather depends on how the platform has its ram arranged (more available as stack or more available as heap) but the distinct advantage of using the heap is that you can programatically ensure that you have allocated enough ram to contain the string even if the string changes length in the future which you can not do with a string allocated on the stack.
Jun 2 '08 #8
Ok then.

Btw,

const char * const mystring = "Hello World";
I can understand why that saves RAM. But still I can't see how this saves PROM. Why does it?

Thanks,
Jun 2 '08 #9
Banfa
9,065 Expert Mod 8TB
I can understand why that saves RAM. But still I can't see how this saves PROM. Why does it?
With some compilers (particularly non-optimising ones) if you do this
Expand|Select|Wrap|Line Numbers
  1. char string1[20];
  2. char string2[20];
  3.  
  4. strcpy(string1, "Hello World");
  5. strcpy(string2, "Hello World");
  6.  
then you end up with 2 copies of the string literal "Hello World" in the data segment, by using a const pointer
Expand|Select|Wrap|Line Numbers
  1. const char * const pHelloWorld = "Hello World";
  2.  
  3. char string1[20];
  4. char string2[20];
  5.  
  6. strcpy(string1, pHelloWorld);
  7. strcpy(string2, pHelloWorld);
  8.  
there is only 1 string literal and it only appears in the data segment once, you save the size of the string minus the size of a pointer in prom.

Now in this example this may not sound very significant, however I worked on an embedded project for a piece of equipment, the front panel (LCD and buttons) for the equipment was control from a separate micro processor board. The program on that board needed extending, however there was no program memory (FLASH in this case) space left. The main contractor declared that in order to extend the program we would have to re-spin the board hardware design to fit a larger flash chip.

However when we examined the code we noticed that the string literal "                    " appeared umpteen times. When that was replaced by a single string literal and a pointer it saved 20k bytes of program space allowing the development to continue without a costly hardware re-spin and the time delay that would have caused.

In case you are wondering it was used very where the LCD needed clearing which suggests to me poorly structured code as I imagine a single function to clear the LCD would have avoided the problem in the first place.
Jun 2 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have...
10
by: slurper | last post by:
if i do this char *mystring="mystring"; later i reassign to mystring like this mystring="replacewithnewstring"; i'm not a c expert, but i suppose i need to get rid of the dynamically...
6
by: kobu.selva | last post by:
I was recently part of a little debate on the issue of whether constants and string literals are considered "data objects" in C. I'm more confused now than before. I was always under the...
8
by: junky_fellow | last post by:
what would be the output for the following piece of code ? if ( "hello" == "hello" ) printf("True\n"); else printf("False\n"); What is the reason for that ?
3
by: steve donovan | last post by:
Hi everyone, I was wondering if anybody had made a proposal for deducing variable type in assigments. This is in effect exactly what is happening in "Dim list As new ArrayList()" and a variant...
6
by: copx | last post by:
Can you / are you supposed to free() string literals which are no longer needed? In my case I've menu construction code that looks like this: menu_items = list_new(); list_add(menu_items,...
17
by: lovecreatesbeauty | last post by:
1. In the following code, is the code (line 11) legal? Is there a notice in the document to tell callers that the parameter s1 should receive an array variable, i.e. type char, but not a variable...
8
by: arnuld | last post by:
i tried to output these 2 to the std. output: const std::string hello = "Hello"; const std::string message = hello + ", world" + "!"; const std::string exclam = "!"; const std::string...
7
by: lithiumcat | last post by:
Hi, I'm not yet very confident in my use of standard terminology, so please be kind if I'm mis-calling something, I will do my best no to make it again once pointed out. I'm wondering what is...
15
by: s0suk3 | last post by:
Hi, I've heard that a string literal has type 'char *' (i.e., a pointer to a char object). But I'm confused as to why this works: char *GetString(void) { return "hello"; }
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.