[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: C program segfaults when run, not under GDB



By default, string constants are put into read only memory pages. You
are getting a SEGV when you try to modify one by s1[c1]=s1[c1+factor];

You can "workaround" it by using the -fwritable-strings in gcc or
something similar in a different c/c++ compiler. However the best way is
to copy the constant to a r/w variable and do your operations on it.
	Yaacov

Eugene Romm wrote:
> 
> Hello.
> 
> I've written a procedure that's supposed to remove all occurances of
> string2 from string1 (parameters).
> For reasons I do not understand, the program compiles but segfaults when
> run from the command prompt, but silently executes without a warning
> when run under GDB. Attached is the program. Segfault occurs on line 29,
> as far as I can tell.
> 
>   ------------------------------------------------------------------------
> #include <stdio.h>
> #define yes 1
> #define no 0
> 
> main() {
>   squeezechar2("abcdeFghijklmnopqrstuvwxyZ","deF");
> }
> 
> squeezechar2(s1,s2)
>      char s1[];
>      char s2[];
> {
>   int c1,c2;
>   int s2length;
>   int factor=0;
>   int moo;
>   int matches=no;
> 
>   for (s2length=0;s2[s2length]!='\0';s2length++); // find out s2length
> 
>   for (c1=c2=0;s1[c1] != '\0' ; c1++) { // loop to end of string
>     if (s1[c1]==s2[c2]) { // if first char matches
>       for (matches=yes,moo=0;(moo<s2length) && (s1[c1+moo]==s2[moo]);moo++);
>       if (moo!=s2length) matches=no;
>       else
>         factor+=s2length; // factor changes if there's a match
>     }
>     //    printf("%c",s1[c1]);
>     if (factor!=0) s1[c1]=s1[c1+factor];
>   }
> }

=================================================================
To unsubscribe, send mail to linux-il-request@linux.org.il with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail linux-il-request@linux.org.il