christheprogrammer
Programmer
Hi All, I am trying to pass a function a char** pointer which was previously allocated via malloc(). Then I want to realloc the array of pointers inside the function but the pointers in the array get screwed..
void pass(char** arr, int* max0, int max1){
int i,j;
(*max0)++;
//Allocate new array in the last spot of arr.
arr = realloc(arr, sizeof(char*)*(*max0));
arr[(*max0)-1] = malloc(sizeof(char)*max1);
for(i=0;i<max1;i++){
// Fill in the new spot
x[(*max0)-1] = i + '0';
}
}
int main(){
char** main_arr;
int i,j,max0,max1;
max0=5;
max1=10;
arr = malloc(sizeof(char*)*max0);
for(i=0;i<max0;i++){
arr = malloc(sizeof(char)*max1);
}
for(i=0;i<max0li++){
for(j=0;j<max1;j++){
arr[j] = i + '0';
}
}
pass(arr,&max0,max1);
printf("ARR is:\n"
for(i=0;i<max0;i++){
for(j=0;j<max1;j++){
printf("%c",arrj[]);
}
printf("\n"
}
}
I get a Segmentation fault on this. I used GDB and found out that the pointers in the char** array are being clobbered upon exit of the function pass. That is, everything seems right until the function exits.
I have spent condiderable time trying to track this down. Any help would be GREATLY appreciated...
(Sorry if there are any stupid syntax errors..)
Thanks Chris
void pass(char** arr, int* max0, int max1){
int i,j;
(*max0)++;
//Allocate new array in the last spot of arr.
arr = realloc(arr, sizeof(char*)*(*max0));
arr[(*max0)-1] = malloc(sizeof(char)*max1);
for(i=0;i<max1;i++){
// Fill in the new spot
x[(*max0)-1] = i + '0';
}
}
int main(){
char** main_arr;
int i,j,max0,max1;
max0=5;
max1=10;
arr = malloc(sizeof(char*)*max0);
for(i=0;i<max0;i++){
arr = malloc(sizeof(char)*max1);
}
for(i=0;i<max0li++){
for(j=0;j<max1;j++){
arr[j] = i + '0';
}
}
pass(arr,&max0,max1);
printf("ARR is:\n"
for(i=0;i<max0;i++){
for(j=0;j<max1;j++){
printf("%c",arrj[]);
}
printf("\n"
}
}
I get a Segmentation fault on this. I used GDB and found out that the pointers in the char** array are being clobbered upon exit of the function pass. That is, everything seems right until the function exits.
I have spent condiderable time trying to track this down. Any help would be GREATLY appreciated...
(Sorry if there are any stupid syntax errors..)
Thanks Chris