Segmentation fault when free

Nash Nipples trashy_bumper at yahoo.com
Sat Sep 20 11:16:41 UTC 2008


> I checked again, up to the this problematic free(),
> functions return newly allocated strings properly:
> 
> char *f( )
> {
>  char *newstr = NULL;
> :
>  newstr = (char *) malloc(p - sp + 1);
>  if (newstr == NULL)
>     return NULL;
>  :
>  return newstr;
> }
> 
> Can a yet not executed wrong free() elsewhere cause a
> problem of this nature?
> 
> Best regards
> Unga
> 
i'm sorry i just dont really cant see a problem with free()
can you please explain it in a more simple way?
it really starts to exceed my screen height

#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 *f(char *d){
  char *newstr = NULL; char *p, *sp;
  sp = malloc(strlen (d)); memcpy(sp, d, strlen(d));
  p = strchr(sp, 44);
  newstr = (char *) malloc(p - sp + 1);
  if (newstr == NULL){
    newstr = malloc(1);
    *newstr = '\0';
    return newstr;  /* you really dont want to return NULL to strlen() */
  }
  *p = '\0';
  memcpy(newstr, sp, sizeof(char) * (p - sp));
  return newstr;
}
char *f1(void){
  char *ab;
  ab = f(abd);
  printf("f1(): %s\n", ab);
  return ab;
}
char *f2(void){
  char *bb;
  bb = f(bbd);
  printf("f2(): %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);
printf("main(): %s\n", c);
free(a);
free(b);
free(c);
}
}



      


More information about the freebsd-questions mailing list