Solved

change constant string

Posted on 2002-07-22
2
222 Views
Last Modified: 2010-04-15
Why the following code can be executed successfully in Unix?
Many books say that constant string can't be changed(strings pointed by pointer is constant). And this code can't be executed in some environment indeed, such as windows.

#include<stdio.h>


main()
{ char *str="hello";
  str[3]='A';
     
printf("string:   %s\n",str);
     
          }
0
Comment
Question by:ww111697
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 50 total points
Comment Utility
>>Why the following code can be executed successfully in Unix?

That depends on the compiler - some place string literals in 'read only' memory areas, causing a segfault. The proper code to apply such a change would be

#include<stdio.h>
#include <string.h>

main()
{

 char *str_const="hello";

 char* str = strdup ( str_const);
 str[3]='A';
   
 printf("string:   %s\n",str);

 free ( str);
   
}

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
If the program attyempts to modify a string literal,
the behavior is undefined.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now