[ale] C and segmentation fault

Joe jknapka at mindspring.com
Fri Jul 18 23:56:10 EDT 1997


I must pick another nit. This may be obvious, but the original
poster may not be aware of it, and there is a stylistic issue
involved:

This code leaks all the memory it mallocs. None of the malloc'd
memory is ever freed, so if a loop executed this code a lot,
the program would eventually grow to fill memory.

IMO it is not generally a good idea to hide malloc and free calls
behind macros, because it makes this sort of problem very hard
to track down. Unless you have a string-handling library that
clearly documents the fact that any string obtained by a call
to STRCPY (equivalent to the standard C call strdup(), BTW)
or STRCAT must be released with a corresponding call to
some companion function, say STRFREE().

And finally, macros that contain multiple statement misbehave
in hard-to-find ways. For example,

char death[] = "Crash-me";
char* copy_from_hell;
if (0)
   STRCPY(copy_from_hell,death); /* Crash here. */

-- Joe Knapka

> If you're going this way, but need the ability to easily append extra
> characters to a string (e.g. s1), to go along with the initial mail
> using pointers, you can try using a couple of macros that I wrote to
> help me out a bit:
> 
> #include <stdlib.h>  /* required for malloc/realloc */
> 
> #define STRCPY(d,s) d=(char *)malloc(strlen(s)+1);strcpy(d,s)
> #define STRCAT(d,s) d=(char *)malloc(d,strlen(d)+strlen(s)+1);strcat(d,s)
> 
> main()
> {
>    char *s1,*s2;
> 
>    STRCPY(s1,"S1");
>    STRCPY(s2,"S2");
>   
>    STRCAT(s1,s2);
>  
>    printf("%s\n",s1);
> }
> 
> 
> ---
> Christopher Hamilton    Internal System Administrator
> chrish at ifsintl.com      IFS International, Inc.






More information about the Ale mailing list