In C, malloc()
is a function that allocates a block of memory on the heap, which is a region of memory separate from the program's stack. The malloc()
function takes one argument, which is the number of bytes to allocate, and returns a pointer to the beginning of the allocated block. If the allocation is unsuccessful, malloc()
returns a null pointer.
Here is an example of using malloc()
to allocate an array of integers:
c
int *my_array = malloc(10 * sizeof(int));
In this example, my_array
is a pointer to the beginning of an array of 10 integers that have been allocated on the heap. The sizeof()
operator is used to determine the size of an integer on the current system, so that the appropriate amount of memory can be allocated.
Once memory has been allocated with malloc()
, it must be freed when it is no longer needed in order to avoid memory leaks. free()
is a function that deallocates memory that was previously allocated with malloc()
. The free()
function takes one argument, which is a pointer to the beginning of the block of memory to be deallocated.
Here is an example of using free()
to deallocate the memory previously allocated for the my_array
array:
c
free(my_array);
In this example, my_array
is the pointer to the beginning of the memory block that was previously allocated with malloc()
. The free()
function deallocates the memory so that it can be reused by the system.
It's important to note that once memory has been freed, it should not be accessed again, as it may have been reallocated to another part of the program or to the operating system. Attempting to access freed memory can result in undefined behavior and can cause program crashes or other unexpected behavior.
No comments:
Post a Comment