Memory Allocation in C
The C compiler has a memory allocation library, defined in malloc.h. Memory is reserved using the malloc function, and returns a pointer to the address. It takes one parameter, the size of memory required in bytes.
The following example allocates space for the string, "hello world".
ptr = (char *)malloc(strlen("Hello world") + 1);
The extra one byte is required to take into account the string termination character, '\0'. The (char *) is called a cast, and forces the return type to be char *.
As data types have different sizes, and malloc returns the space in bytes, it is good practice for portability reasons to use the sizeof operator when specifying a size to allocate.
The following example reads a string into the character array buffer and then allocates the exact amount of memory required and copies it to a variable called "ptr".
#include <string.h>
#include <malloc.h>
int main()
{
char *ptr, buffer[80];
printf("Enter a string: ");
gets(buffer);
ptr = (char *)malloc((strlen(buffer) + 1) *
sizeof(char));
strcpy(ptr, buffer);
printf("You entered: %s\n", ptr);
return 0;
}
The output of the program will be as follows:
Enter a string: India is the best
You entered: India is the best |
|