[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: C program segfaults when run, not under GDB
- To: <milesteg(at-nospam)surfree.net.il>
- Subject: Re: C program segfaults when run, not under GDB
- From: Behdad Esfahbod <behdad(at-nospam)bamdad.org>
- Date: Sun, 25 Nov 2001 22:31:54 +0330 (IRT)
- cc: <linux-il(at-nospam)linux.org.il>
- Delivered-To: linux.org.il-linux-il@linux.org.il
- In-Reply-To: <3C00BBB9.4060905@bezeqint.net>
- Sender: linux-il-bounce(at-nospam)cs.huji.ac.il
Hi,
Your program has a few bugs (beside the style problems):
1. It just does not work when there is more than one occurence of s2
in s1, because you are just moving s1[c1+factor] to s1[c1], and the
matching of s1+c1 with s2 cannot be performed at the same time.
2. s1[c1+factor] can reach beyond the end of s1.
3. You should not alter a string defined with double-quotes, this is
the reason of sigsegv, when you run it, that portion of memory is
read-only, while in gdb this is not the case, you should first copy it
to a buffer, then call squeezechars2 on it.
Fixed code attached (with a linear algorithm).
behdad
On Sun, 25 Nov 2001, 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.
>
--
Behdad
4 Azar 1380, 2001 Nov 25
[Finger for Geek Code]
-- Attached file included as plaintext by Listar --
-- File: s.c
#include <stdlib.h>
#include <string.h>
void squeezechar2(char *st, char *subst);
int
main() {
char p[100];
strcpy(p, "abcdeFghijklmnopqrsdeFtuvwxyZ");
squeezechar2(p,"deF");
printf(p);
return 0;
}
void
squeezechar2(char *s1, char *s2)
{
int c1,c2;
int s2length;
int factor;
for (s2length=0;s2[s2length]!='\0';s2length++); // find out s2length
for (c1=c2=factor=0; s1[c1] != '\0' ; c1++) { // loop to end of string
s1[c1-factor]=s1[c1];
if (s1[c1]==s2[c2])
c2++;
else
c2=0;
if (c2 == s2length) {
c2=0;
factor+=s2length;
}
}
s1[c1-factor] = 0;
}
=================================================================
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