Linux libc-Doku
Files | |
file | stdlib.h |
Functions | |
void * | malloc (size_t size) |
Allocate memory. More... | |
void | free (void *ptr) |
Free allocated memory. More... | |
Detailed Description
With malloc() (memory allocation) a program can request memory from the operating system. The allocated memory is usable until it is free()'d again. It is important, that programs always check if a malloc() call was successful and free their memory after usage, otherwise a so-called memory leak exists.
// allocate memory
if (s == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
// use allocated memory
strcpy(s, "Hello World\n");
printf("%s", s);
// free allocated memory
free(s);
Function Documentation
void* malloc | ( | size_t | size | ) |
The malloc() function allocates size
bytes at the heap and returns a pointer to the allocated memory or NULL
if an error has been occurred. Be aware, that the memory is not initialized after a successful call to malloc().
- Parameters
-
size number of bytes to be allocated
- Return values
-
NULL on error, errno
is set!=NULL pointer to allocated memory
void free | ( | void * | ptr | ) |