I have this function which should copy a node in a linked list(not first of it)
struct Node {
char* data;
Node* next;
};
void Insert(Node*head, int index, char* data) {//find a is function to find needed position
Node* temp = find(head, index);
Node* t = (Node*)malloc(sizeof(Node));
t->data = (char*)malloc(100);//where the problem is //line 4
strcpy(t->data, data);
t->next = temp->next;
temp->next = t;
}
it will work well if line 4 is in my code. I have read this question:
crash-or-segmentation-fault-when-data-is-copied-scanned-read-to-an-uninitializ
so I know pointer cannot contain any data and I cannot copy/store data into a pointer. So, as you see I allocated memory for it first and then placed data in it, otherwise my program will crash.
But then I used this: t->data = data;
and it worked, so I want to know: why when I use strcpy
like this strcpy(t->data, data);
, I need to allocate memory for t->data
first, otherwise my program will crash; but this t->data = data;
will work well, without the requirement to allocate memory?
Can you explain this to me?
PS:casting malloc is because of using c++ compiler.