I am trying to make a linked list implementation in C, I then decided to implement the same logic to create a 'string', essentially the same linked list with more functions, mainly to create the linked list object from an input string. The code works perfectly well when given a small input string like 35 characters, but crashes at the first time malloc runs when the input string is bigger. Now I have tried to run this code on a different machine and it works perfectly with any size string(below 1000 smth characters), so I suspect there is a problem with my machine here are the functions at cause:
struct Map
{
char val;
struct Map *next;
};
void makeString(struct Map **head, char *needStr){
int i = 0;
while (needStr[i] != '\0'){
insert(head, needStr[i]);
i++;
}
}
void insert(struct Map **head, char value){
printf("%c", value);
if ((*head) == NULL)
{
(*head) = (struct Map *)malloc(sizeof(struct Map));
(*head)->val = value;
(*head)->next = NULL;
}
else
{
struct Map *cur = *head;
while (cur->next != NULL)
{
cur = cur->next;
}
struct Map *New = (struct Map *)malloc(sizeof(struct Map));
New->val = value;
New->next = NULL;
cur->next = New;
}
}
int main()
{
struct Map *list = NULL;
char *a = (char*) malloc(sizeof(char));
scanf("%[^\n]",a);
makeString(&string, a);
}
To provide a more visible understanding of the problem, here is an example:
Input:
Hello, how are you?
Output:
Hello, how are you?
code works, runs all other functions called in main.
Input: "******************************************************************************************************************************************************"
Output: "*"
vscode points out an error in malloc inside the insert function, and it happens on the first iteration.