Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

segmentation fault doubt

Status
Not open for further replies.

isaisa

Programmer
May 14, 2002
97
IN
hi all
i am getting the segmentation fault when i try to execute the code mentioned below. is there any specific in the storage of string literal that is causing this ?

Code:
    char *str1;
    str1=(char *) malloc (100);
    str1="hello";
    cout<<str1;
    free(str1);
    cout<<str1;
    return 0;

can anybody explain me the reason and how the constants are alloted memory ?

thanks in advance

sanjay
 
> str1="hello";
Yes, this overwrites the pointer you allocated.
So when you call free(), it isn't what you malloc'ed.

Try
strcpy( str1, "hello" );

Also, your 2nd cout is invalid, you can't reference memory after you have called free(). Sure, it might 'work' here, but sooner or later, your code will be in big trouble.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top