I have the following structs:
typedef struct{
char *name;
int size;
void *data;
} Struct1;
typedef struct st2{
char *name;
struct st2 **Struct2array;
Struct1 **Struct1array;
int Struct1_n;
int Struct2_n;
} Struct2;
where the double pointers in Struct2 are used as dynamic arrays of pointers to other Struct2's or Struct1's. The data in Struct1 is used as a dynamic array to store some data. Struct1_n and Struct2_n represent the number of elements inside of their respective dynamic arrays.
When I make a variable of type Struct1, I fill the data by casting a char * to a void * and using memcpy to copy it into data. If I then cast to data back into a char pointer, I can get back the contents and they are generally the same. However, for some reason the values that data in Struct1 is pointing to change after the following line:
struct2pointer->Struct1array[struct2pointer->Struct1_n - 1] = struct1pointer;
Examples:
printf("%d\n", *(char *)(struct1pointer->data));
gives the value of the 1stbyte of struct1pointer->data as -96 immediately after the problematic line regardless of the value it printed immediately before(which was the same one memcpy-d into data). if I add 1 to the pointer before casting it to a char pointer(2nd byte) it always gives 32, if I add 2 (3rd byte)it always gives 96 and so on.
Why is this happening when the struct1pointer is on the right side of the assignment operator and what can be done to fix this?
EDIT:
Functions where content changes:
void struct2_addstruct1(Struct2 struct2pointer, Struct1 *struct1pointer){
struct2->Struct1_n++;
struct2pointer->Struct1array = realloc(struct2pointer->Struct1array, struct2->Struct1_n * sizeof(Struct1 *)); //edited to remove increment that was added on accident, isn't in the original code
struct2pointer->Struct1array[struct2pointer->Struct1_n - 1] = struct1pointer;
}
The function that creates Struct1:
void struct1_init(Struct1 *s, char *name, void *data, int size){
s->name = malloc(strlen(name) + 1);
strcpy(s->name, name);
s->size = size;
s->data = malloc(size);
memcpy(s->data, data, size);
}
This is how that funcion is called when creating struct1:
Struct1 *s;
struct1_init(s, name, data, size);
name, data and size are provided form the outside but shouldn't have anything to do with the problem.