-1

Hi
I have written this Program which create a list of books which is given by the User and i can't free the my_value at the end of program and get a lot of errors .
This is my Code

#include <stdio.h>
#include <stdlib.h>


int main(){



int n;
printf("Please Enter the Number of Books:\n");
scanf("%d",&n);
char **array=(char *) malloc((n+1)*sizeof(char *));

for(int i=0;i<n;i++){
 array[i] = (char *)malloc(sizeof(char *));
}

for(int i=0;i<n;i++){
char *my_value=(char *) malloc(sizeof(char)*100);
printf("Please Enter the Name of the %dth Book:\n",i+1);
scanf("%s",my_value);
*(array+i)=my_value;
free(my_value);

}

for(int i=0;i<n;i++){
 printf("\n The Book Nr.%d is %s \n",i+1,*(array+i));
}
for(int i=0;i<n;i++){
 free(array[i]);
}
free(array);


return 0 ;
}
  • What sort of errors do you get? Which platform are you developing on? Have you used [Valgrind](http://valgrind.org/)? You should show some sample data and report the errors you get from that sample data. Maybe just two books worth of data; that'd be sufficient, probably. Please read about how to create an MCVE ([MCVE]), noting that data and output (actual vs expected) are both parts of an MCVE. – Jonathan Leffler Dec 09 '17 at 00:52
  • You do not need to cast the result of `malloc`. See [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Additionally, `char **array=(char *) malloc((n+1)*sizeof(char *))` has incompatible pointer types. – Galen Dec 09 '17 at 01:02

1 Answers1

1

First, in

char **array=(char *) malloc((n+1)*sizeof(char *));

you don't need n+1 pointers since you use only n.

Then, this loop

for(int i=0;i<n;i++){
   array[i] = (char *)malloc(sizeof(char *));
}

is unnecessary (and wrong). array[i] is to be overwritten just after.

In the next loop

*(array+i)=my_value; // is array[i] = my_value
free(my_value);      // <=== why? remove that line!

you free what you just allocated -- array[i] cannot be used anymore from that point! Lead to undefined behavior.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100