Segmentation fault when free
Nash Nipples
trashy_bumper at yahoo.com
Fri Sep 19 20:14:09 UTC 2008
--- On Fri, 9/19/08, Unga <unga888 at yahoo.com> wrote:
> From: Unga <unga888 at yahoo.com>
> Subject: Segmentation fault when free
> To: freebsd-questions at freebsd.org
> Date: Friday, September 19, 2008, 9:17 AM
> Hi all
>
> I'm running FreeBSD 7 on i386. I have a C program
> compiled with gcc 4.2.1 20070719.
>
> Logically my program is:
>
> char *a;
> char *b;
> char *c;
>
> while (cond)
> {
> a = f1(); /* malloc() and send a string */
> b = f2(); /* malloc() and send a string */
>
> c = (char *) malloc(strlen(a) + strlen(b) + 1);
> c[0] = '\0';
>
> strcat(c, a);
> strcat(c, b);
>
> free(a);
> free(b);
> }
>
> When it executes free(b), my program exits with
> Segmentation fault: 11. The free(a) executes well.
>
> The problem is with free(b). Even swap free(b) first and
> free(a) next, it still crashes at free(b).
>
> If I comment out free() lines, further down the program,
> first few characters of one string get dropped when executes
> a completely unrelated line.
>
> How could I bit more narrow down the problem?
>
> Many thanks in advance.
>
> Kind regards
> Unga
>
>
im affraid i didnt implement your request correctly but the program below did not crash my server under root in 60 seconds
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *a;
char *b;
char *c;
char *abd = "Hi, im a string 1\0";
char *bbd = "Hey, im a string 2\0";
char *f1(void){
char *ab;
ab = malloc(strlen (abd));
memcpy(ab, abd, strlen(abd));
printf("f1(): %s\n", ab);
return ab;
}
char *f2(void){
char *bb;
bb = malloc(strlen (bbd));
memcpy(bb, bbd, strlen(bbd));
printf("f1(): %s\n", bb);
return bb;
}
int
main(void)
{
while (1)
{
a = f1(); /* malloc() and send a string */
b = f2(); /* malloc() and send a string */
c = (char *) malloc(strlen(a) + strlen(b) + 1);
c[0] = '\0';
strcat(c, a);
strcat(c, b);
free(a);
free(b);
}
}
More information about the freebsd-questions
mailing list