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".
char *ptr, buffer;
printf("Enter a string: ");
ptr = (char *)malloc((strlen(buffer) + 1) *
printf("You entered: %s\n", ptr);
The output of the program will be as follows:
Enter a string: India is the best
You entered: India is the best
|Sample Chapters from book DATA RECOVERY WITH AND WITHOUT PROGRAMMING by Author Tarun Tyagi
Publishers of the Book
Number of Pages
Price of the Book
BPB Publications, New Delhi, India
$69.00 (Including Shipping Charges, Cost of Book and Other expenses, Free Source Code CD included with the Book)