The function accepts an array of zero or more strings that has a NULL in the last location. It frees all memory allocated for the array for strings.

Question

void free strings (char **strings);

The function accepts an array of zero or more strings that has a NULL in the last location. It frees all memory allocated for the array for strings.

Here is an example of some code that would create such an array, using the function copy_string from the page Allocating Strings:

array(char **) calloc(6, sizeof (char*));

array[0]=copy\ str ing(^ prime dog^ prime prime ) ;

array[1]* opy\ str ing(^ prime cat^ prime prime ) ; array[2]* opy\ 5tr ing(^ 11ama^ ) ;

array * [3] -string(“mule”) ;

array[4]=co( lng(^ fish^ ) ;

Why are you passing 6 to calloc when there are only 5 strings?

Note that this array has five strings in it, but will require six calls to free, one for each allocated string and one for the array itself!

Write your solution in the window below labeled Code. At any time you can press the Test button below to send your solution to a remote system for testing. The compilation and testing results will appear in the second window below labeled Result. When you have completed the quiz, press Submit to submit your solution.

Here is a complete starter file including the header file you will need to include. freestrings.h does include both string.h and stdio.h so you do not have to include those.

#include freestrings.h"

void free strings (char **strings)
{

}

 

Explanation

To free memory when a pointer is dynamically allocated, we utilize the ‘free’ keyword. The technique of assigning the data in the double-pointer is not specified in the above query.
If the data is stored in the double-pointer using malloc, we must first free the memory for each array element before freeing the double-pointer.
If the data is indirectly assigned, we only need to free the double-pointer.
We use indirect assignment in the following example because we are unfamiliar with the mode of assignment. We then deallocate memory by using free just for the double-pointer.
The needed code is as follows:

Code

#include<stdio.h>
#include<conio.h>

//function prototype
void free_strings( char **strings);

//main function
void main()
{	char **array= (char**)calloc(6, sizeof(char*));
    int i;
    //stored string at addresses
    char str1="dog", str2="cat", str3="llama", str4="mule", str5="fish";
    
    //assign values to double pointer;
    array[0]=str1;
    array[1]=str2;
    array[2]=str3;
    array[3]=str4;
    array[4]=str5;
    
    //function call to free the memory
    free_strings(array);

}

void free_strings( char **strings)
{	
    free(strings);
    printf("Free strings run successfully");
    
}

Output

 

 

Also, read check the python code below that doesn’t work properly, adjust it, and explain?

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *