home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / c / 12251 < prev    next >
Encoding:
Internet Message Format  |  1992-08-12  |  2.1 KB

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