I am having problems assigning ptr->str to token value. Not sure whats going on ptr->str is pointer to char so is token. The printf is not printing char value. I am getting a runtime error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "C2A6E4_List-Driver.h"
typedef struct List
{
struct List *next; /* pointer to the next list node */
char *str; /* pointer to the string represented */
int count; /* # of occurrences of this string */
} List;
#endif
#define LINESIZE 256
#define DELIMETERS " "
typedef enum { false, true }bool;
List *newNode(void);
bool searchNode(List *head, char *key);
List *CreateList(FILE *fp)
{
List *head, *ptr;
int cnt = 0;
size_t length;
bool firstNode = true;
bool srchResult = false;
char buf[LINESIZE];
while (fgets(buf, (int)sizeof(buf), fp) != NULL) { /* read line of file*/
char *token = strtok(buf, DELIMETERS);
while (token != NULL) {
if (firstNode) {
ptr = newNode();
length = strlen(token) + 1;
// ptr->str = (char *)malloc(sizeof(char) * length);
ptr->next = head;
ptr->str = token;
ptr->count = 1;
head = ptr;
firstNode = false;
}
else {
srchResult = searchNode(head, token);
printf("srchResult= %d\n", srchResult);
if (srchResult) {
ptr = newNode();
length = strlen(token) + 1;
ptr->next = head;
ptr->str = token;
printf("ptr_str = %s", ptr->str);
ptr->count += 1;
head = ptr;
}//end if
}
printf("token = %s\n", token);
token = strtok(NULL, DELIMETERS);
}//end while
}// end while fgets
return head;
}
List *newNode(void)
{
List *ptr = (List *)malloc(sizeof(List));
if (ptr == NULL) {
fputs("Out of Memory\n ", stderr);
exit(EXIT_FAILURE);
}
return ptr;
}
bool searchNode(List *head, char *key)
{
List *cur = head;
bool cmpResult = false;
printf("key = %s\n", key);
while (cur) {
printf("call strmcmp\n");
printf("cur->str = \n", cur->str);
cmpResult = strcmp(cur->str, key);
printf("cmpResult = %d\n", cmpResult);
if (cmpResult == 0) {
return false;
cur->count += 1;
}
cur = cur->next;
printf("curnext\n");
}
if (cmpResult > 0 || cmpResult < 0)
cmpResult = true;
printf("return\n");
return cmpResult;
}
List *PrintList(const List *head)
{
List *cur = head;
while (cur) {
printf(" %s %d ea\n", cur->str, cur->count);
cur = cur->next;
}
return (List *)head;
}
void FreeList(List *head)
{
List *cur = head, *tmp;
while (cur) {
tmp = head;
head = head->next;
free(tmp);
}
}