Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!mimsy!oddjob!gargoyle!ihnp4!chinet!john From: john@chinet.UUCP (John Mundt) Newsgroups: comp.lang.c Subject: Re: Allocation for pointers Message-ID: <1486@chinet.UUCP> Date: Sat, 5-Sep-87 17:50:58 EDT Article-I.D.: chinet.1486 Posted: Sat Sep 5 17:50:58 1987 Date-Received: Sun, 6-Sep-87 09:08:04 EDT References: <1357@faline.bellcore.com> <27282@sun.uucp> Reply-To: john@chinet.UUCP (John Mundt) Organization: Chinet - Public Access Unix Lines: 56 In article <27282@sun.uucp> guy%gorodish@Sun.COM (Guy Harris) writes: >> main() >> { char *a; >> a = "text"; >> recurs(a); >> } >> >> void recurs(a); >> char *a; >> { strcat(a,"more text"); >> if (some conditional test) recurs(a); >> } >> >> As I understand it, I'm passing the address of the variable a into >> the routine recurs. When the program was compiled, "text" was placed into the static area of the object code along with other static variables. a was then assigned to point to the beginning of the string. When you use strcat to append more text, you will merrily rub out whatever static data was kept beyond the 5 bytes assigned to store "text\0". Strange and wonderful things will happen when the static area is overrun and you get out into other sections of the program. The only safe way to do what you want is to either pre-assign a with enough memory to hold whatever you'll put into it, as in char a[BUFSIZ]; or to get the size of the present a, the size of the piece you want to append + 1 byte for the \0, and call malloc() to hold the new string. You should probably free the old string. in recurs(a) char *a; { ... int len; char *ptr, malloc(); len = strlen(a) len += strlen(string_you_want_to_add); ptr = malloc(len + 1); strcpy(ptr, a); strcat(ptr, string_you_want_to_add); free(a) return(ptr); ... } Up in main, you have to make a = recurs(a) each time you call it. You should add error checking to see that malloc returns a valid pointer too. John Mundt ...ihnp4!chinet!john Teachers' Aide, Inc. ...ihnp4!chinet!teachad!fred