Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Allocating memory for strings

Node:Allocating memory for strings, Next:, Previous:Bits and pieces, Up:Bits and pieces



Allocating memory for strings

Neither of the methods above is any good if a program is going to be fetching a lot of strings from a user. It just isn't practical to define lots of static strings and expect the user to type into the right size boxes! The next step in string handling is therefore to allocate memory for strings personally: in other words to be able to say how much storage is needed for a string while a program is running. C has special memory allocation functions which can do this, not only for strings but for any kind of object. Suppose then that a program is going to get ten strings from the user. Here is one way in which it could be done:

  1. Define one large, static string (or array) for getting one string at a time. Call this a string buffer, or waiting place.
  2. Define an array of ten pointers to characters, so that the strings can be recalled easily.
  3. Find out how long the string in the string buffer is.
  4. Allocate memory for the string.
  5. Copy the string from the buffer to the new storage and place a pointer to it in the array of pointers for reference.
  6. Release the memory when it is finished with.

 
 
  Published under free license. Design by Interspire