I made this C function for easy reading of strings from the console. Can someone please help and find if there are any faults(like a memory leak) in the following code? Which line would the fault be in? I dont know assembly programming and all.
Code:
#include<stdio.h>
#include<stdlib.h>
//global structures and variables
typedef char* PtrString;
//function declarations
PtrString readString(void);
//function definitions
int main(int argc, char *argv[]){
PtrString name;
puts("What is your name?");
name = readString();
printf("Hello %s\n",name);
return 0;
}
PtrString readString(void)
{
//declarations
struct ele{char ch; struct ele *next;};
typedef struct ele Ele;
Ele *first = NULL, *last = NULL, *curr = NULL;
int ch = 0;
long int count = 0;
char *str = NULL;
int index = 0;
//dummy node
first = (Ele*)malloc(sizeof(Ele));
if(first == NULL)
{puts("Error: Cannot read characters as there is no memory available."); goto EndIt;}
first->ch = '\0';
first->next = NULL;
last = first;
//read user input one character at a time into a linked list
while(1)
{
ch = getchar();
if(ch == '\n')
{
break;
}
else
{
curr = (Ele*)malloc(sizeof(Ele));
if(curr==NULL)
{
puts("Error: Cannot read characters as there is no memory available.");
goto EndIt;
}
curr->ch = ch;
curr->next = NULL;
last->next = curr;
last = curr;
curr = NULL;
count++;//we also count the number of characters read in
}
}
printf("count = %d\n",count);
//create array
str = (char *)malloc(sizeof(char)*(count+1));
if(str != NULL)
{
//copy characters from linked list into array
index = 0;
curr = first->next;
while(curr != NULL)
{
str[index] = curr->ch;
curr = curr->next;
index++;
}
str[index] = '\0';
}
else
{
puts("Error: Cannot make string as there is no memory available.");
goto EndIt;
}
EndIt:
//destroy linked list, if necessary
curr = first;
while(curr != NULL)
{
first = first->next;
free(curr);
curr=first;
}
//return actual string or NULL
return str;
}