I am getting the segmentation faults Unable to rectify it...........
If function is used (multi line commented at the top) im finding segemntation fault With the present code i am unable to guess the segmentation fault.
If fixed size of string like malloc is used then it works very fine.
//Array of pointers method
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int count=0;
char *** input(char ***);
void print(char ***);
/*
void *allocate(char *p,int j)
{
int i=0;
do
{
p=realloc(p,i+1);
// printf("p[count][j]= %u\n",p);
p[i]=getchar();
}while(p[i++]!=10);
p[i-1]='\0';
return p;
}*/
void save(char ***p)
{
int j,i;
FILE *fp;
fp=fopen("Secret.c","w");
for(i=0;i<count;i++)
for(j=0;j<3;j++)
{
fprintf(fp,"%s\n",p[i][j]);
}
fclose(fp);
}
void main()
{
char ***a=0;
char ch;
// printf("a = %u\n ",a);
while(1)
{
if(count>0)
{
printf("a = %lu\n",a);
printf("*a = %lu\n",sizeof(*a));
printf("**a = %lu\n",sizeof(**a));
printf("***a = %lu\n",***a);
}
printf("\n\n\t\t\tMenu\n\n\n");
printf("i . input\ns . save\np . print\nq . quit");
printf("\n\nEnter your choice : ");
scanf(" %c",&ch);
getchar();
switch(ch)
{
case 'i': a=input(a);break;
case 's': save(a);
case 'p': print(a);break;
case 'q': return;
default : printf("\n\n\t\t!!! Invalid choice \n\n");
}
}
}
char *** input(char ***p)
{
int i=0,j;
// printf("p = %u\n ",p);
p=realloc(p,sizeof(p)*(count+1));
// printf("p = %u\n ",p);
// printf("sizeof(p) = %u\n",sizeof(p));
// printf("*p = %u\n ",*p);
for(j=0;j<3;j++)
{
p[count]=realloc(p[count],sizeof(p)*(j+1));
// printf("*p = %u\n ",*p);
// printf("**p = %u\n ",**p);
i=0;
if(j==0)
printf("Enter the %d name : ",count+1);
else if (j==1)
printf("Enter the %d mobile no : ",count+1);
else
printf("Enter the %d E-mail : ",count+1);
// p[count][j]=malloc(20);
// gets(p[count][j]);
// p[count][j]=allocate(p[count][j],j);
do
{
p[count][j]=realloc(p[count][j],i+1);
p[count][j][i]=getchar();
}while(p[count][j][i++]!=10);
p[count][j][i-1]='\0';
// printf("***p = %u %s\n ",***p,***p);
}
count++;
return p;
}
void print(char ***p)
{
int j,i;
for(i=0;i<count;i++,printf("\n"))
for( j=0;j<3;j++)
printf("p[%d][%d] : %s\t",i,j,p[i][j]);
}
p=realloc(p,sizeof(p)*(count+1))I am pretty sure you should take a size of something else thanphere...pto begin with and thenreallocsome reasonably anticipated additional number ofpif your original limit is reached. Do notreallocfor every element you add. (you can, but your are killing your efficiency with repeated calls torealloc)