[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

change constant string

Posted on 2002-07-22
2
Medium Priority
?
232 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 200 total points
ID: 7169842
>>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
ID: 7171049
If the program attyempts to modify a string literal,
the behavior is undefined.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

656 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