Hi there,

On executing the above code I'm getting the error "segmentation fault". Is it possible to manipulate a string variable which already contains a data?

#include<stdio.h>

int main()
{
           char *str="Hello";
           char * str1 ="World";

           strcpy(str,str1);

           printf("%s",str);
}

Recommended Answers

All 5 Replies

you cant copy a string into an unallocated pointer location.

change line 5 to char str[16]; (for example)


.

Thank u. But, I.m having problem with a char pointer like this.
char **str;

for str I've allocated memory dynamically. But, still I'm not able to do this.

*(*str+0)+0 = *(*(str+0)+1);

please help me out. I'm struck with this.

@ajithasati
Post your troubled code with the dynamic allocation part.
Don't post it HERE in a snippet code section. This is not the proper venue.
Create a new thread, and ask your question. If you ask correctly you might be helped.

Older compilers and linkers would allow you to "clobber" the compiled-in strings, but newer compilers discourage it. It is not portable, but more important, it invites viruses since there is real code stored near the compiled-in string, which could be modified by overrunning the end of the array (referred to as "buffer overflow").

Newer compilers would give you an error message on

char *str="Hello";

which should be

const char *str="Hello";

, and another error on

strcpy(str, str1);

since it is declared as strcpy(char *, const char *);
In this context, "const char *" means "the character(s) being pointed toward are read-only".

Adding further to the what UncleLeroy has stated
If you have some code of this sort

char* str= "ABCDEF";
str[1]='A';

You will get a seg fault. I THINK that is because the string "ABCDEF" is stored in the code section of the process and any attempt to modify it results in a run time erorr

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.