I have question about pointers in C. Each pointer has 4 bytes in memory (address). When I call malloc() it only allocates memory and put it's address to the pointer, also free() only frees the memory that pointer is pointing to. But how can I delete pointer (4 bytes) in memory that I no longer need ? Isn't there a memory leak ?
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.
delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
The free() function is used in C++ to de-allocate the memory dynamically. It is basically a library function used in C++, and it is defined in stdlib. h header file. This library function is used when the pointers either pointing to the memory allocated using malloc() function or Null pointer.
The pointer itself is a regular variable, which means that when it goes out of scope those 4 bytes allocated for it will automatically be freed, just like any other variable you might have declared on that same scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With