home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!uknet!ox-prg!oxuniv!atmtjkv
- From: atmtjkv@vax.oxford.ac.uk
- Newsgroups: comp.lang.c
- Subject: Re: Allocate memory to typed in string, How?
- Message-ID: <1992Aug12.082216.8205@vax.oxford.ac.uk>
- Date: 12 Aug 92 07:22:16 GMT
- References: <bibhas.712893811@femto.engr.mun.ca> <bibhas.713109464@femto.engr.mun.ca> <MJN.92Aug9012538@pseudo.uucp>
- Organization: Oxford University VAX 6620
- Lines: 42
-
- In article <MJN.92Aug9012538@pseudo.uucp>, mjn@pseudo.uucp (Murray Nesbitt) writes:
- >
- > In article <bibhas.713109464@femto.engr.mun.ca> bibhas@pico.engr.mun.ca (Bibhas Bhattacharya) writes:
- >
- >>I wrote a simple function to take care of any arbitrary length string
- >>input. It doesn't take any argument, returns a pointer to the string.
- >>Here's how it might look in a program. Hope this helps someone new to
- >>C like me.
- >>
- >
- >> scanf("%c",&temp);
- >> if(string == (char *)NULL)
- >> string=(char *) malloc(sizeof(char));
- >> else
- >> string = (char *) realloc(string, (numchar+1) *
- >> sizeof(char));
- >
- > You can do without the above conditional: just call realloc()
- > unconditionally (as you've already initialized ``string'' to NULL, and
- > with a NULL first argument realloc() behaves like malloc()). The loop
- > will run faster without the conditional.
- >
- > As well, you should check the return value of realloc(), and return
- > NULL if there is a failure.
- > Murray
- > --
- --
- Faster than reallocing with one extra byte each time is to store the
- number of bytes allocated separately, and then doubling it each time
- the string length exceeds the allocated space. This obviously
- has a memory penalty, but reduces the number of system requests,
- making the allocation go as log(string length) rather than (string length).
- It's not worth it with very short strings, but the initial allocation
- can be larger than 1 byte, if you can spare the memory.
- (I use this technique in a plot driver for sunwindows, which stores each page
- in a buffer to allow subsequent redisplay or filtering; the strings in that
- case can be 8K long!)
-
- Tim Kingsmill-Vellacott
- Atmospheric, Oceanic and Planetary Physics
- University of Oxford, UK.
- tjkv@atm.ox.ac.uk preferred
-