1

I'm really confused by the bug I encountered tonight. When assigning value to an element in an array, another element is changed and I can't figure out what happened. And I don't know if I used sizeof() correctly. However they seem to work fine after adding intensive output statement. The problem appears to be in line 11, but I have no idea on how to fix it. Here is my code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void addstr(char ***arr, const char *str, int *size){
  char *my_str=(char *)calloc(strlen(str)+1,sizeof(char));
  strcpy(my_str,str);
  char **new_arr=realloc(*arr,sizeof(*arr)+sizeof(char*));
  /*for (int i=0;i<*size;i++)
    printf("%s\n",new_arr[i]);*/
  new_arr[*size]=my_str;
  /*for (int i=0;i<*size;i++)
    printf("%s\n",new_arr[i]);*/
  *arr=new_arr;
  *size=*size+1;
}

int main(){
  char **mystery=0;
  int size=0;
  const char *ptr1="test1";
  const char *ptr2="test2";
  const char *ptr3="test3";
  const char *ptr4="test4";
  const char *ptr5="test5";
  const char *ptr6="test6";
  addstr(&mystery,ptr1,&size);
  addstr(&mystery,ptr2,&size);
  addstr(&mystery,ptr3,&size);
  addstr(&mystery,ptr4,&size);
  addstr(&mystery,ptr5,&size);
  addstr(&mystery,ptr6,&size);
  int i;
  printf("\nresult:\n\nsize: %d\n",size);
  for (i=0;i<size;i++)
    printf("%s\n",mystery[i]);
}

The output is

result:

size: 6
test1

test3
test4
test5
test6

test2 somehow is changed. This is driving me mad cause I'm still new to c and don't know where exactly went wrong. Can anyone help please?

mnille
  • 1,328
  • 4
  • 16
  • 20
i54cxy
  • 35
  • 4

0 Answers0