LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   problem in source code (https://www.linuxquestions.org/questions/linux-general-1/problem-in-source-code-236597/)

dileepkk 09-29-2004 07:13 AM

How to modify an initialised string
 
Hi,

here is small segment of code:
Code:

#include <stdio.h>
main()
{
char *src="linux";
*(src+0)='L';
printf("%s",src);
}

Iam getting SEGMENTATION FAULT because of the statement
Code:

*(src+0)='L';
why it is so ???
And, how to change the content of the above string??

Thanks in advance

Dileep

m00t00 09-29-2004 07:31 AM

you're derefrencing it. meaning when you change src[0] to L, you're actually changing the first part of the address it points to. when you call printf, printf tries to print from some nonexistant address, and you segfault.

try changing it to:

src[0]='L'

wpyh 09-29-2004 12:14 PM

#include <stdio.h>
main()
{
char *src="linux";
src[0]='L';
printf("%s",src);
}

This code gives me a segfault...

proudclod 09-29-2004 02:28 PM

erm, what are you compiling it with?

If it's strict it might be worth adding in

return 0;

wpyh 09-29-2004 07:32 PM

gcc 3.4.2

Well, this _does_ segault too:
#include <stdio.h>
int main()
{
char *src="linux";
src[0]='L';
printf("%s",src);
return 0;
}

wpyh 09-29-2004 07:36 PM

A preinitialized string is a constant. At least, we shouldn't modify it because it points to a data area that's not writable by us (I think). This works:

#include <stdio.h>
main()
{
char *src = malloc(6);
strcpy(src, "linux");
printf("%s\n", src);
*(src+0)='L';
printf("%s\n", src);
return 0;
}

So it's not actually a problem with Linux, but with the program itself..


All times are GMT -5. The time now is 10:32 AM.