Question: What is wrong with my c code below? I am trying to practice malloc. Here in this code, I want to declare pointer to pointer,

What is wrong with my c code below?

I am trying to practice malloc. Here in this code, I want to declare pointer to pointer, and each pointed pointer will point to a single charcter which is a casted value from integer. I tried run this code and when I tried testing it with valgrind, it gave me a bunch of errors including memory leak and invalid read/write of 1. The fact I want to confirm is whether I should free() the char* before I free() char**, because when I learned about struct and free() of them, I've heard that malloc'd pointers should be free()d before I free() the struct. And, I want to check if this applies to every data structure.

The command I used for valgrind testing is this:

valgrind --leak-check=yes ./a.out

#include #include int main(){ char **charptr = malloc(sizeof(char*)*20); for (int i = 1; i < 20; i++){ *(charptr+i) =(char*) malloc(sizeof(char)); } for (int i = 0; i < 20; i++){ **(charptr+i) = (char )i; printf("%s ", *(charptr+i) ); } for (int i = 1; i < 20; i++){ free (*(charptr+i)); } free(charptr); return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!