Memory Handling in C & C++
Memory Handling in C & C++
FUNCTIONS
IN
C / C++
ABSTRACT
Gives knowledge about memory handling functions in c
& c++
Includes syntax and examples which makes easier to
understand and easy to program
Functions explained are
C C++
Malloc new
Calloc delete
Realloc
Free
MALLOC
malloc allocates a block of size bytes from the memory
heap. It allows a program to allocate memory explicitly
as it's needed, and in the exact amounts needed.
The heap is used for dynamic allocation of variable-
sized blocks of memory.
SYNTAX :
void *malloc(size_t size);
Example:
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <process.h>
int main(void)
{
char *str;
/* display string */
printf("String is %s\n", str);
/* free memory */
free(str);
return 0;
}
CALLOC
calloc provides access to the C memory heap, which is
available for dynamic
allocation of variable-sized blocks of memory.
SYNTAX :
void *calloc(size_t nitems, size_t size);
Example:
#include <stdio.h>
#include <alloc.h>
#include <string.h>
int main(void)
{
char *str = NULL;
/* display string */
printf("String is %s\n", str);
/* free memory */
free(str);
return 0;
}
FREE
free deallocates a memory block allocated by a
previous call to calloc,
malloc, or realloc.
SYNTAX :
void free(void *block);
free example
#include <string.h>
#include <stdio.h>
#include <alloc.h>
int main(void)
{
char *str;
/* display string */
printf("String is %s\n", str);
/* free memory */
free(str);
return 0;
}
REALLOC
realloc adjusts the size of the allocated block to size,
copying the
contents to a new location if necessary.
SYNTAX :
void *realloc(void *block, size_t size);
realloc example
#include <stdio.h>
#include <alloc.h>
#include <string.h>
int main(void)
{
char *str;
/* free memory */
free(str);
return 0;
}
MEMCPY
these functions copies a block of n bytes from src to
dest.
With memcpy, if src and dest overlap, the behavior is
undefined.
SYNTAX :
void *memcpy (void *dest, const void *src, size_t n);
memcpy example
#include <stdio.h>
#include <string.h>
int main(void)
{
char src[] = "******************************";
char dest[] = "abcdefghijlkmnopqrstuvwxyz0123456709";
char *ptr;
SYNTAX :
void *memset (void *s, int c, size_t n);
Example:
#include <string.h>
#include <stdio.h>
#include <mem.h>
int main(void)
{
char buffer[] = "Hello world\n";
Syntax:
þ <pointer_to_name> = new <name> [ <name_initializer> ];
þ delete <pointer_to_name>;
The storage duration of the new object is from the point of creation until
the operator "delete" deallocates its memory, or until the end of the
program.
Example:
name *nameptr; // name is any non-function type
...
if (!(nameptr = new name)) {
errmsg("Insufficient memory for name");
exit (1);
}
// Use *nameptr to initialize new name object
...
delete nameptr; //destroy name; deallocate
sizeof(name) bytes