The start of a string, as mentioned earlier, is indicated by a pointer to a variable of type char. You might recall how to declare such a pointer:
char *message;
This statement declares a pointer to a variable of type char named message. It doesn"t point to anything now, but what if you changed the pointer declaration to read:
char *message = "Great Caesar"s Ghost!";
When this statement executes, the string Great Caesar"s Ghost! (with a terminating null character) is stored somewhere in memory, and the pointer message is initialized to point to the first character of the string. Don't worry where in memory the string is stored; it's handled automatically by the compiler. Once defined, message is a pointer to the string and can be used as such.
The preceding declaration/initialization is equivalent to the following, and the two notations *message and message[] also are equivalent; they both mean a pointer to
char message[] = "Great Caesar"s Ghost!";
This method of allocating space for string storage is fine when you know what you string you need when writing the program. What if the program has varying string storage needs, depending on user input or other factors that are unknown when you"re writing the program? You use the malloc() function, which lets you allocate storage space on the-fly
The malloc() Function
The malloc() function is one of C's memory allocation functions. When you call malloc(), you pass it the number of bytes of memory needed. malloc() finds and reserves a block of memory of the required size and returns the address of the first byte in the block. You don't need to worry about where the memory is found; it's handled automatically
The malloc() function returns an address, and its return type is a pointer to type void. Why void? A pointer to type void is compatible with all data types. Because the memory allocated by malloc() can be used to store any of C"s data types, the void return type is appropriate.
#include
void *malloc(size_t size);
malloc() allocates a block of memory that is the number of bytes stated in size. By allocating memory as needed with malloc() instead of all at once when a program starts, you can use a computer"s memory more efficiently. When using malloc(), you need to include the STDLIB.H header file. Some compilers have other header files that can be included; for portability, however, it"s best to include stdlib.h.
malloc() returns a pointer to the allocated block of memory. If malloc() was unable to allocate the required amount of memory, it returns null. Whenever you try to allocate memory, you should always check the return value, even if the amount of memory to be allocated is small.
Example 1
#include <stdio.h>
#include <stlib.h>
int main(void)
{
/* allocate memory for a 100-character string */
char *str;
str = (char *) malloc(100);
if (str == NULL)
{
printf( "Not enough memory to allocate buffer");
exit(1);
}
printf( "String was allocated!
" );
return 0;
}
Example 2
/* allocate memory for an array of 50 integers */
int *numbers;
numbers = (int *) malloc(50 * sizeof(int));
Example 3
/* allocate memory for an array of 10 float values */
float *numbers;
numbers = (float *) malloc(10 * sizeof(float));
Using the malloc() Function
You can use malloc() to allocate memory to store a single type char. First, declare a pointer to type char:
char *ptr;
Next, call malloc() and pass the size of the desired memory block. Because a type char usually occupies one byte, you need a block of one byte. The value returned by malloc() is assigned to the pointer:
ptr = malloc(1);
This statement allocates a memory block of one byte and assigns its address to ptr. Unlike variables that are declared in the program, this byte of memory has no name. Only the pointer can reference the variable. For example, to store the character 'x" there, you would write
*ptr = 'x";
Allocating storage for a string with malloc() is almost identical to using malloc() to allocate space for a single variable of type char. The main difference is that you need to know the amount of space to allocate—the maximum number of characters in the string. This maximum depends on the needs of your program. For this example, say you want to allocate space for a string of 99 characters, plus one for the terminating null character, for a total of 100. First you declare a pointer to type char, and then you call malloc():
char *ptr;
ptr = malloc(100)
Now ptr points to a reserved block of 100 bytes that can be used for string storage and manipulation. You can use ptr just as though your program had explicitly allocated that space with the following array declaration:
char ptr[100];
Using malloc() lets your program allocate storage space as needed in response to demand. Of course, available space is not unlimited; it depends on the amount of memory installed in your computer and on the program"s other storage requirements. If not enough memory is available, malloc() returns null (0). Your program should test the return value of malloc() so that you"ll know the memory requested was allocated successfully. You always should test malloc()"s return value against the symbolic constant NULL, which is defined in stdlib.h. Any program using malloc() must #include the header file stdlib.
Note:
Literal values were used to allocate space for characters in the above examples. You should always multiply the size of the data type you are allocating space for by the amount of space you want. The above allocations assumed that a character was stored in just one byte. If a character is stored in more than one byte, then the above examples will overwrite other areas of memory. For example:
ptr = malloc(100);
should really be declared as
ptr = malloc( 100 * sizeof(char));
Write a function to allocate storage space for string data
/* Demonstrates the use of malloc() to allocate storage */
/* space for string data. */
#include <stdio.h>
#include <stlib.h>
char count, *ptr, *p;
int main(void)
{
/* Allocate a block of 35 bytes. Test for success. */
/* The exit() library function terminates the program. */
ptr = malloc(35 * sizeof(char));
if (ptr == NULL)
{
puts("Memory allocation error.");
return 1;
}
/* Fill the string with values 65 through 90, */
/* which are the ASCII codes for A-Z. */
/* p is a pointer used to step through the string. */
/* You want ptr to remain pointed at the start */
/* of the string. */
p = ptr;
for (count = 65; count < 91 ; count++)
*p++ = count;
/* Add the terminating null character. */
*p = '";
/* Display the string on the screen. */
puts(ptr);
free(ptr);
return 0;
}
Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Note:
Don't allocate more memory than you need. Not everyone has a lot of memory, so you should try to use it sparingly.
Dont'T try to assign a new string to a character array that was previously allocated only enough memory to hold a smaller string. For example, in this declaration:
char a_string[] = "NO";
a_string points to "NO". If you try to assign "YES" to this array, you could have serious problems. The array initially could hold only three characters—"N", 'O", and a null. "YES" is four characters—"Y", 'E", 'S", and a null. You have no idea what the fourth character, null, overwrites.