I’m just learn about memory dynamic, and did experiment, but still get stuck. already search some around, but didn’t give any result.
This is my simple code :
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct kata kata;
struct kata {
char string[256];
};
void load(kata **data)
{
int len = 0;
while( len < 5 ) {
(*data) = (kata *) realloc ((*data), (len + 1) * sizeof(kata));
printf("copy A - %d\n", len);
strcpy(data[len]->string, "A");
len++;
}
getch();
}
int main() {
kata *data = NULL;
load(&data);
}
and my question, why it’s always segmentation fault (at 3) when i debug it ?
thanks a lot for your advice
EDIT :
Still don’t know why the error occurs, but i’ve found the solution just now..
just modify data[len]->string to (*data)[len].string
any idea, why we call data[len]->string occur some random segfault ?
data[len]->stringshould be(*data)[len]->string(*data)[len].string