This program works perfectly:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 2
int tempfunction (char **comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";
*(comments+0)=(char *) malloc(strlen(str1)+1);
*(comments+1)=(char *) malloc(strlen(str2)+1);
strcpy(*(comments+0), str1);
strcpy(*(comments+1), str2);
return 0;
}
int main(void)
{
char **comments;
/* This is the section I am talking about */
comments=(char **) malloc(MAX_NUM*sizeof(char *));
if (comments==NULL)
{
printf("\n### ERROR: malloc failed.\n");
exit(EXIT_FAILURE);
}
/* Upto here............................. */
tempfunction(comments);
printf("%s%s", comments[0], comments[1]);
return 0;
}
But for future convenience I would like to put the malloc
section inside the tempfunction
. When I do that, I get a segmentation fault error.
I thought it might be due to initialization, so instead of char **comments;
I write:
char a = 'a';
char *P = &a;
char **comments = &P;
But, it still doesn't work. I would be very grateful if you could help me understand why this happens and how to fix it.