C free() function
C free() function - Free allocated memory
Syntax:
void free(void *ptr)
The free() function is used to free a block of storage. The ptr argument points to a block that is previously reserved with a call to the calloc(), malloc(), realloc().
Parameters:
Name | Description | Required /Optional |
---|---|---|
ptr | Previously allocated memory block to be freed. | Required |
Return value from free()
- There is no return value.
Example: free() function
The following example shows the usage of free() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(10);
strcpy(str, "w3resource");
printf("String = %s, Address = %u\n", str, str);
/* Deallocate allocated memory */
free(str);
return(0);
}
Output:
String = w3resource, Address = 7738336
C Programming Code Editor:
Previous C Programming: C calloc()
Next C Programming: C malloc()
C Programming: Tips of the Day
Returning an array using C
You can't return arrays from functions in C. You also can't (shouldn't) do this:
char *returnArray(char array []){ char returned [10]; //methods to pull values from array, interpret them, and then create new array return &(returned[0]); //is this correct? }
returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.
You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.
Dynamically allocate the memory inside of the function (caller responsible for deallocating ret)
char *foo(int count) { char *ret = malloc(count); if(!ret) return NULL; for(int i = 0; i < count; ++i) ret[i] = i; return ret; }
Call it like so:
int main() { char *p = foo(10); if(p) { // do stuff with p free(p); } return 0; }
Ref : https://bit.ly/3yFIeao
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook