I am sending this message to clear my confusion that I could not manage and handle.
The foo1 function code should work. I am giving the code details for you.
When I run the code, the result is a segmentation error at line 12. Then I made a little change in foo2 in different syntax notation. foo2 is working. But I want to learn more deeply how pointers work. Which kind of error can cause this error. If I don't use line 12 everything looks fine. What would be the main reason for this issue. Could you please assist me?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int foo1(char ***BufferArray,char *item,int idx);
int foo2(char ***BufferArray,char *item,int idx);
int main(){
char **ptr=malloc(sizeof(char*)*3);
char a[]="hello0";
char b[]="hello1";
char c[]="hello2";
foo1(&ptr,a,0);
//foo1(&ptr,b,1);//Exception has occurred. Segmentation fault //line 12
printf("[%s]",*(ptr+0));
printf("[%s]",*(ptr+1));
getchar();
return(0);
}
int foo1(char ***BufferArray,char *item,int idx){
int n;
n=1;
**(BufferArray+idx)=malloc(sizeof(char)*strlen(item));
strcpy(**(BufferArray+idx),item);
return(0);
}
int foo2(char ***BufferArray,char *item,int idx){
int n;
char **temp=*BufferArray;
*(temp+idx)=malloc(sizeof(char)*strlen(item));
strcpy(*(temp+idx),item);
*BufferArray=temp;
return(0);
}
You are passing to the function
foo1a pointer to the pointer
ptrdefined likeSo to access the pointer within the function you may use an expression either like
*BufferArrayor like*( BufferArray + 0 )or like BufferArray[0].In the function
foo2you are in fact using one of these expressionsAn expression like that
*(BufferArray+idx)used in the functionfoo1where the variableidxis greater than0tries to access memory outside the passed pointer that invokes undefined behavior when the expression is further dereferenced.Pay attention to that strings contain trailing zero character
'\0'. You need to reserve memory also to it if you are going to copy a string in the allocated memory. That is you need to write for exampleUsing
sizeof( char )in the call ofmallocis redundant and makes the line kess readable. Instead you could write simply