I'm stuck doing something that shouldn't be that hard, I want to add element to my char** but when I try to add some elements to my first array then some to my second sometime it doesn't work depending of where I declare my second array ...
The error code I have is : "realloc(): invalid pointer\nAbandon (core dumped)"
int main(void)
{
char *a = "aaa";
char *b = "bbb";
char *c = "ccc";
char *d = "ddd";
char *e = "eee";
char **s1 = malloc(sizeof(char*));
if(s1 == NULL) printf("wkwk\n");
*s1 = NULL;
int size1 = 0;
char **s2 = malloc(sizeof(char*)); // the problematic line is here
if(s2 == NULL) printf("blbl\n");
*s2 = NULL;
int size2 = 0;
array_add(s1,a,&size1);
array_add(s1,b,&size1);
array_add(s1,c,&size1);
array_add(s2,d,&size2);
array_add(s2,e,&size2);
// printing
return 0;
}
void array_add(char **array,char *string,int *nb_elem)
{
array = realloc(array,sizeof(array)+sizeof(string));
if(array == NULL) exit(EXIT_FAILURE);
array[*nb_elem] = malloc(sizeof(string));
if(array[*nb_elem] == NULL) exit(EXIT_FAILURE);
strcpy(array[*nb_elem],string);
*nb_elem = *nb_elem + 1;
}
I don't know why but if I malloc s2 after the first array_add(s1,a,&size1)
it works without problem (I haven't tried with more array tho).
Comments
Post a Comment