Question

Simple C program performing unexpectedly

Asked by: pankajtiwary

Hi,
      I have not seen a program doing something unexpected like this. Its a very simple code.

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

int main() {
    char* str = "Hello";
    printf("Before strcpy str is %s\n", str);
    strcpy(str, "Hi");
    printf("After strcpy str is %s\n", str);
    return 0;
}

Output:-
Before strcpy str is Hello
Segmentation fault

I am not able to know what is happening behind the scenes. One more thing is if the str is declared as char str[] = "Hello", the program runs with no errors.

Please explain me the strange output.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-08-21 at 22:40:42ID20716930
Tags

c

,

program

,

simple

,

strcpy

Topic

C Programming Language

Participating Experts
7
Points
50
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Removing printf function
    I'm trying to take out the line that reads "Must enter at least one character!" from the following program of mine but I can't work out how to do it right. I thought could just take out the whole if function: if ( (len = noSpace(aCopy)) == 0 ) { ...
  2. strcpy() or malloc() problem !!
    hi, i have to tried to create a program which should display n last line from a file specified at command line. here is the code (i called it mylast.c) ###################### #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h&...
  3. printf
    void split(char *pMessage) { int slen, leng; char *pE, *pF; slen = strlen(pMessage) ; pE = pMessage; do { pF = pE; leng = slen > MAXLEN ? MAXLEN : slen ; pE = pF + leng; while (*pE != ' ') { if (*pE...
  4. printf()
    Hello experts, For the printf function to work we have to include the <stdio.h> library. But when i look into the library i find only the interface for that function. Where is the actual library linked from? thanx, teena
  5. printf and scanf
    I am trying to scan a word (string) in middle of a sentence. i am using printf and scanf.... (probably thats very basic, but i am still new to the stuff). i want to input a word and then be able to continue with the phrase without going to the next line example printf("...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: hienhienPosted on 2003-08-21 at 23:11:29ID: 9201040

because you are using a pointer ( *str)

you should use this line as well

   char* str = strdup("Hello");

after that your program will no errors

 

by: compEmikeyPosted on 2003-08-21 at 23:12:24ID: 9201044

I think you're declaring that the variable remain constant or so, if you wanted to set it up as a pointer, the initialization would look like this:

char *str = "Hello";

I haven't written C in about 3 months, but I believe this is how you set it up.  I'm not sure setting it to a pointer like that will work or not, so you might need to malloc before you assign value(s) to the string.

 

by: compEmikeyPosted on 2003-08-21 at 23:13:45ID: 9201054

The difference between your and mine, if you can't tell, is that your asterisk is by the char and mine is by the str.  They mean two different things.

 

by: knightmadPosted on 2003-08-21 at 23:15:58ID: 9201063

Well, when you declare your string as char* str = "Hello"; you don't perform any memory allocation, all you do is to point your variable to a constant array of characters in memory ("Hello"). This is why you get segmentation fault when trying to strcpy it. I didn't tested the program with str[], but you should make your code look like this:

#define A_BIG_VALUE 100
int main() {
   char* str;
   str  = (char *) malloc(A_BIG_VALUE); // for example, or char str[A_BIG_VALUE].
   strcpt(str,"Hello");
   printf("Before strcpy str is %s\n", str);
   strcpy(str, "Hi");
   printf("After strcpy str is %s\n", str);
   return 0;
}

 

by: robert_marquardtPosted on 2003-08-21 at 23:35:14ID: 9201148

There is a difference between char *str = "Test"; and char str[] = "Test";
The first one declares a pointer variable pointing to a constant char array which means that the area is not writable.
The second one gives the char area the name str and initializes it with "Test". That area is now not const.
You should be able to change the behavior with a compiler switch to make the string literals writable.

 

by: andrewjbPosted on 2003-08-21 at 23:51:08ID: 9201209

char *str = "Hello";
char* str = "Hello";
char    *       str    =     "Hello"       ;

Are all identical.

There's only a difference between

char *a,*b;
and
char* a,b;

because the '*' really lives with the 'a' and not the 'char'
so the first one means
char *a;
char *b;
whereas the second means
char *a;
char b;

The reason your original fails, is that char *str = "Hello"; makes 'str' point to the string. Fine. But, because you're setting it to a fixed value, that string lives in a particular 'fixed' bit of memory that the compiler has prepared for you. You're not allowed to change it. Depending on the implementation, the strcpy() might fail, or you find it fails later. You're not allowed to overwrite the memory that str points to. If you want to strcpy(str,...) you need to allocate some new memory for it somewhere, using malloc()

So, you'd have to do

   char* str = "Hello";
   printf("Before strcpy str is %s\n", str);
   str = (char*) malloc( 3 );    // 2 characters in 'Hi' + 1 for the NULL
   strcpy(str, "Hi");
   printf("After strcpy str is %s\n", str);
   free(str);

Free() is required else you'll leak the memory you malloced. You don't free the original (from str = "Hello"), because that's in the 'fixed' memory area.

 

by: compEmikeyPosted on 2003-08-21 at 23:53:34ID: 9201219

When "malloc"ing, I wouldn't recommend using a big value if you know exactly how long your longest string will be.  Give yourself some headroom, but don't waste memory by allocating a big slot for something as small as Hello or Hi.  If Hello is going to be your longest, for instance, mallocing 8 bytes should be more than enough, each character being 1 byte, plus some headroom.  

 

by: pankajtiwaryPosted on 2003-08-22 at 00:30:13ID: 9201338

Hi all,
 robert_marquardt's comment was brief and explaining. Actually I was not expecting this output. Now I understand that in case of an array char str[] = "Hello", the string literal and the variable str are both created on stack and both can be modifies using any means. But if the initilization is done with char* str = "Hello", there is no memory allocation for str and so strcpy fails. Correct me if I am wrong.
But I don't understand one thing. str points to the first byte where the first charecter 'H' is stored. When I print str, it prints successfully. That means the area where "Hello" is stored is in my access and so I don't get any segmentation fault while reading the contents of that memory location. Buyt I don't understand one thing. Whay can't I write to that momery location. One more thing. Consider this piece of code.

int main() {
   char str[] = "Hello";
   printf("Before strcpy str is %s\n", str);
   printf("%s, %p, %p\n", str, str, &str);
   strcpy(str, "Hi");
   printf("After strcpy str is %s\n", str);
   return 0;
}

while printing addresses, the thing that amazed me is str and &str both give the same thing. And I don't understand this. PLease help me.

 

by: robert_marquardtPosted on 2003-08-22 at 01:40:37ID: 9201620

char *str = "Test"; declares a variable str of type pointer and a anonymous static constant array (the string literal) and makes the pointer point to it.
char str[] = "Test"; only declares a variable of char array and initializes it with the string literal. There is no constant array anymore.

The ccrucial point is that the anonymous constant array for the string literal is placed in a read only memory area.
This allows the compiler to eliminate duplicate strings. You can make this area writable and supress the elimination of duplicate strings with compiler options.
The crash comes from strcpy writing to write protected memory.

 

by: pankajtiwaryPosted on 2003-08-22 at 03:08:28ID: 9201957

I have got a lot of funda from robert_marquardt 's comment, but I have still not received the answer of the second question. Why do str and &str print the same value? Is it printf that is doing something or anything else. Can someone of you explain?

Thanks a lot

 

by: chofreitherPosted on 2003-08-22 at 04:33:40ID: 9202270

Well, str is an array. In C, simply mentioning the name of the array like 'str', without any brackets,  means getting the address of the array. As you surely know, & is the address-of operator, so it is logical that it does the same thing.

 

by: pankajtiwaryPosted on 2003-08-22 at 05:12:27ID: 9202479

Well, I think there is a confusion here. the name of the array i.e. str contains the first element of the memory space where the string "Hello" resides. It means the value of str will be XYZ where 'H' resides at the address XYZ. Upto here I think I am correct. Now &str should give the address of str i.e. where str resides. I think these 2 things should be different. We consider an example scenario.

Lets say the memory is assigned as follows:-

0x00001 contains 'H'
0x00002 contains 'e'
...
...
0x00005 contains 'o'
0x00006 contains '\0'

str is somewhere say at 0x00011.
So, the content of str is the address of 'H' i.e.
str=0x00001

and &str contains the address of str i.e.
&str=0x00011

So, the 2 values should be different. Please correct me if I am wrong. And can you explain me things with the scenario presented above. I think I am just near to the solution :-)

Thanks a lot again

 

by: chofreitherPosted on 2003-08-22 at 06:10:02ID: 9202946

The behaviour you are expecting can be generated as follows:

char *strptr = str;
printf("%p %p\n", strptr, &strptr);

This does what you expect it to do because C treats a pointer as a variable in its own right, the semantics for an array are subtly different.

 

by: kirsteng123Posted on 2003-08-22 at 13:15:43ID: 9206398

The answer to your question lies in the c-faq:
http://www.faqs.org/faqs/C-faq/faq/

I paste the question for your convenience:
1.32:      What is the difference between these initializations?

            char a[] = "string literal";
            char *p  = "string literal";

      My program crashes if I try to assign a new value to p[i].

A:      A string literal can be used in two slightly different ways.  As
      an array initializer (as in the declaration of char a[]), it
      specifies the initial values of the characters in that array.
      Anywhere else, it turns into an unnamed, static array of
      characters, which may be stored in read-only memory, which is
      why you can't safely modify it.  In an expression context, the
      array is converted at once to a pointer, as usual (see section
      6), so the second declaration initializes p to point to the
      unnamed array's first element.

      (For compiling old code, some compilers have a switch
      controlling whether strings are writable or not.)

      See also questions 1.31, 6.1, 6.2, and 6.8.

      References: K&R2 Sec. 5.5 p. 104; ISO Sec. 6.1.4, Sec. 6.5.7;
      Rationale Sec. 3.1.4; H&S Sec. 2.7.4 pp. 31-2.

 

by: pankajtiwaryPosted on 2003-08-24 at 23:13:21ID: 9214325

Hi all,
    Thanks a lot for your help. Sorry friends, I think the points should be split and thats what I did.

Thanks again.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...