circular linked list not working properly in c windows - c

I tried to implement circular linked list to manage a set of tasks by a server side application. The application is multi-threaded where one thread (updater() ) reads the linked list only for read while another two (push_stream() and delete_stream()) access the linked list to add to and delete from the linked list respectively.
My problem is not all the files to be deleted (after being processed) are deleted.
struct data_stream
{
bool processed;
int count;
char filename[30];
int TYPE_GRP;
int task_type;
struct data_stream *next;
};
struct data_stream *stream_head=NULL; //global variable
main(partial code)
main()
{
_beginthread(updater, 0, NULL);
while ((new_socket = accept(srv_sock, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
_beginthreadex(0, 0, handle_client, &new_socket, 0, 0);
}
}
handle_client function (partial code)
handle_client()
{
//some where in handle_client
EnterCriticalSection(&stream_lock);
stream_head = push_stream(&stream_head, TYPE_GRP, task_type);
LeaveCriticalSection(&stream_lock);
}
updater function (full source code)
void updater(void *data)
{
while (1)
{
struct data_stream*temp = stream_head;
struct data_stream*first = stream_head;
struct data_stream*prev = NULL;
if (stream_head != NULL)
{
struct data_stream*next = NULL;
do
{
next = temp->next;
if (temp->processed == false&&temp->task_type == 2)
{
process_files(temp);
}
else if (temp->processed == false&&temp->task_type == 3)
{
process_others();
}
EnterCriticalSection(&stream_lock);
temp->processed = true;
LeaveCriticalSection(&stream_lock);
temp = next;
} while (temp != first);
}
if (stream_head != NULL)
{
EnterCriticalSection(&stream_lock);
stream_head=delete_stream(&stream_head);
LeaveCriticalSection(&stream_lock);
}
Sleep(6000);
}
}
process_files
void process_files(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
printf("\nerror opening file\n");
}
process_others()
void process_others(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
{
printf("\nerror opening file\n");
}
}
}
push_stream (full source code)
struct data_stream* push_stream(struct data_data_stream**head_ref, int typ_grp, int task_type)
{
struct data_stream*new_data_stream=
(struct data_data_stream*)malloc(sizeof(struct data_stream));
new_stream->processed = false;
new_stream->task_type = task_type;
new_stream->TYPE_GRP = typ_grp;
new_stream->filename[0] = NULL;
new_stream->count = 0;
new_stream->next = NULL;
if (task_type == 2)
sprintf_s(new_stream->filename, "%s%03d.txt", "file_md5_list_", stream_count);
else
sprintf_s(new_stream->filename, "%s%03d.txt", "other_list_", stream_count);
if (*head_ref == NULL)
{
*head_ref = new_stream;
new_stream->next = new_stream;
}
else
{
struct data_stream* last = (*head_ref)->next;
struct data_stream* prev = (*head_ref)->next;
while (last != *head_ref)
{
prev = last;
last = last->next;
}
new_stream->next = *head_ref;
last->next = new_stream;
}
if (stream_count > 998)
stream_count = 1;
else
stream_count++;
return new_stream;
}
delete_stream function (full source code)
struct data_stream* delete_stream(struct data_data_stream**head)
{
if (head == NULL)
return NULL;
struct data_stream*prev = NULL;
struct data_stream*temp = *head;
struct data_stream*first = *head;
do
{
struct data_stream*next = temp->next;
if (temp->processed)
{
if (prev == NULL)
*head = temp->next;
else
prev->next = temp->next;
char file_to_delete[50] = { NULL };
memcpy_s(file_to_delete, strlen(temp->filename), temp->filename, strlen(temp->filename));
DeleteFileA(file_to_delete);
free(temp);
}
else
{
prev = temp;
}
temp = next;
} while (temp != first);
if (prev == NULL)
{
return NULL;
}
return *head;
}

Related

doubly linked list problem with removal and push back maybe

In the main function, I tried to push front couple numbers and push back couple numbers and then remove pos = 0 and pso = 1. However, in the output, remove at pos = 0 and remove at pos = 1 prints out number 5 and number 7 which are wrong. It should be 4 and 2. I cannot find which part I am wrong. Here is my code:
#ifndef MYDLL_H
#define MYDLL_H
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *previous;
} node_t;
typedef struct DLL
{
int count;
node_t *head;
node_t *tail;
} dll_t;
dll_t *create_dll()
{
dll_t *myDLL = (dll_t*)malloc(sizeof(dll_t));
if (myDLL == NULL) {
return NULL;
}
myDLL->count = 0;
myDLL->head = NULL;
myDLL->tail = NULL;
return myDLL;
}
int dll_empty(dll_t *l)
{
if (l == NULL) {
return -1;
}
if (l->count == 0 && l->head == NULL) {
return 1;
} else {
return 0;
}
}
int dll_push_front(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->next = l->head;
new->previous = NULL;
if (l->head != NULL) { //set new prev for the previous head before pushing.
l->head->previous = new;
}
l->head = new; // reset the new head for l.
l->count++;
return 1;
}
int dll_push_back(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->previous = l->tail;
new->next = NULL;
if(l->tail != NULL) {
l->tail->next = new;
} else {
l->head = new;
}
l->tail = new;
l->count++;
return 1;
}
int dll_pop_front(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->head;
int pop_item = pop_pointer->data;
t->head = pop_pointer->next; // set new head.
if (t->head != NULL) {
t->head->previous = NULL;
} else { // t->head = NULL cuz only one item and after popping, the t->head is null.
t->tail = NULL; // else if t->head = NULL, then t->tail also should be NULL.
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_pop_back(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->tail;
int pop_item = pop_pointer->data;
t->tail = pop_pointer->previous;
if (t->tail != NULL) {
t->tail->next = NULL;
} else {
t->head = NULL;
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_insert(dll_t *l, int pos, int item)
{
if (l == NULL) {
return -1;
}
if (pos >= l->count || pos < 0) {
return 0;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return 0;
}
new->data = item;
if(pos == 0) {
return dll_push_front(l, item);
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
//ex: pos = 1, no for loop, pointer still head.
new->previous = pointer;
new->next = pointer->next;
pointer->next->previous = new;
pointer->next = new;
l->count++;
return 1;
}
int dll_get(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
return pointer->data;
}
int dll_remove(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
node_t* prev = NULL; // first node prev is null.
for (int i = 0; i < pos; i++) {
prev = pointer;
pointer = pointer->next;
}
if (prev == NULL) { // first item.
l->head = pointer->next;
} else {
prev->next = pointer->next;
}
if (pointer->next != NULL) {
pointer->next->previous = prev;
}
// if we are removing the tail node
if (pointer == l->tail) {
l->tail = prev;
}
int removed_value = pointer->data;
free(pointer);
l->count--;
return removed_value;
}
int dll_size(dll_t *t) {
if (t == NULL) {
return -1;
}
return t->count;
}
void free_dll(dll_t *t)
{
if (t == NULL) {
return;
}
if (t == NULL) {
free(t);
return;
}
node_t* pointer = t->head;
while(pointer != NULL) {
node_t* pointer2 = pointer;
pointer = pointer->next;
free(pointer2);
}
free(t);
}
#endif

Shell simulation using lists

Now i'm learning C and I have a problem with memory alocation, atleast this I understand from my code error.
Code
#ifndef __FILE_H__
#define __FILE_H__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct Files Files;
typedef struct DirList DirList;
typedef struct NodeFile NodeFile;
typedef struct NodeDir NodeDir;
typedef struct Directory {
// The name of the directory
char *name;
// TODO: The list of files of the current directory
Files *files;
// TODO: The list of dirs of the current directory
DirList *dirs;
// The parent directory of the current directory (NULL for the root
// directory)
struct Directory *parentDir;
} Directory;
// DO NOT MODIFY THIS STRUCTURE
typedef struct File {
// The name of the file
char *name;
// The size of the file
int size;
// The content of the file
char *data;
// The directory in which the file is located
Directory *dir;
} File;
typedef struct Files {
NodeFile *first;
NodeFile *last;
} Files;
typedef struct DirList {
NodeDir *first;
NodeDir *last;
} DirList;
typedef struct NodeFile {
struct NodeFile *next;
struct NodeFile *prev;
File *newfile;
} NodeFile;
typedef struct NodeDir {
struct NodeDir *next;
struct NodeDir *prev;
Directory *newdir;
} NodeDir;
// create root of file system
void makeroot(Directory **root)
{
*root = (Directory *) malloc(sizeof(Directory));
(*root)->parentDir = NULL;
(*root)->name = strdup("/");
(*root)->files = NULL;
(*root)->dirs = NULL;
}
// remove root of file system
void deleteroot(Directory *root)
{
root = NULL;
free(root);
}
//add new file to current directory
File *touch(Directory *root, char *nume, char *content)
{
NodeFile *new = (NodeFile *) malloc(sizeof(NodeFile));
new->newfile = (File *) malloc(sizeof(File));
new->newfile->name = (char *) malloc(strlen(nume) + 1);
new->newfile->data = (char *) malloc(strlen(content) + 1);
strcpy(new->newfile->name, nume);
strcpy(new->newfile->data, content);
if (root->files == NULL) {
root->files = (Files *) malloc(sizeof(Files));
root->files->first = (NodeFile *) malloc(sizeof(NodeFile));
root->files->last = (NodeFile *) malloc(sizeof(NodeFile));
//if no file in folder root has first and last position
root->files->first = new;
root->files->last = new;
} else if (strcmp(root->files->first->newfile->name,
new->newfile->name) > 0) {
new->next = root->files->first;
root->files->first = new;
} else if (strcmp(root->files->last->newfile->name,
new->newfile->name) < 0) {
root->files->last->next = new;
root->files->last = new;
} else {
NodeFile *i = root->files->first;
while (i != root->files->last) {
if (strcmp(i->next->newfile->name,
new->newfile->name) > 0) {
if (i == root->files->first->next)
i = root->files->first;
i->next->prev = new;
new->next = i->next;
new->prev = i;
i->next = new;
break;
}
i = i->next;
}
}
return new->newfile;
}
// Create directory
Directory *mkdir(Directory *parent, char *name)
{
NodeDir *new = (NodeDir *) malloc(sizeof(NodeDir));
//new->newdir = (Directory *) malloc(sizeof(Directory));
new->newdir = (Directory *) malloc(strlen(Directory) + 1);
new->newdir->name = (char *) malloc(strlen(name) + 1);
strcpy(new->newdir->name, name);
new->newdir->parentDir = parent;
if (parent->dirs == NULL) {
parent->dirs = (DirList *)malloc(sizeof(DirList));
parent->dirs->first = (NodeDir *) malloc(sizeof(NodeDir));
parent->dirs->last = (NodeDir *) malloc(sizeof(NodeDir));
parent->dirs->first = new;
parent->dirs->last = new;
} else if (strcmp(parent->dirs->first->newdir->name,
new->newdir->name) > 0) {
new->next = parent->dirs->first;
parent->dirs->first = new;
} else if (strcmp(parent->dirs->last->newdir->name,
new->newdir->name) < 0) {
parent->dirs->last->next = new;
parent->dirs->last = new;
} else {
NodeDir *i = parent->dirs->first->next;
while (i != NULL) {
if (strcmp(i->newdir->name, new->newdir->name) > 0) {
if (i == parent->dirs->first->next)
i = parent->dirs->first;
i->next->prev = new;
new->next = i->next;
new->prev = i;
i->next = new;
break;
}
i = i->next;
}
}
return new->newdir;
}
// traverse list and print files and folders names
void ls(Directory *parent)
{
if (parent->files != NULL) {
NodeFile *i;
for (i = parent->files->first; i != NULL; i = i->next)
printf("%s ", i->newfile->name);
}
if (parent->dirs != NULL) {
NodeDir *j;
for (j = parent->dirs->first; j != NULL; j = j->next)
printf("%s ", j->newdir->name);
}
printf("\n");
}
// working directory
void pwd(Directory *dir)
{
if (dir->parentDir == NULL)
return;
if (dir->parentDir != NULL) {
pwd(dir->parentDir);
printf("/%s", dir->name);
}
}
Directory *cd(Directory *dir, char *where)
{
if (strcmp(where, "..") == 0 && dir->parentDir != NULL) {
return dir->parentDir;
} else if (dir->dirs == NULL)
printf("Cannot move to ‘%s’: No such directory!\n", where);
else {
NodeDir *it = dir->dirs->first;
while (it != NULL) {
if (strcmp(it->newdir->name, where) == 0) {
dir = it->newdir;
break;
}
it = it->next;
}
if (it == NULL)
printf("Cannot move to ‘%s’: No such directory!\n",
where);
free(it);
}
return dir;
}
void tree(Directory *parent, int i)
{
if (i == 1)
printf("\n%s\n", parent->name);
if (parent->files != NULL) {
NodeFile *it;
for (it = parent->files->first; it != NULL; it = it->next) {
if (i != 1) {
int j;
for (j = 0; j < i; j++)
printf(" ");
}
printf(" %s\n", it->newfile->name);
}
free(it);
}
if (parent->dirs != NULL) {
NodeDir *it = parent->dirs->first;
while (it != NULL) {
int j;
for (j = 0; j < i; j++)
printf(" ");
printf("%s\n", it->newdir->name);
i = i + 1;
tree(it->newdir, i);
it = it->next;
i = i - 1;
}
free(it);
}
}
void rm(Directory *parent, char *dirname)
{ //it -- item
NodeFile *it;
for (it = parent->files->first; it != NULL; it = it->next) {
if (strcmp(it->newfile->name, dirname) == 0) {
if (it == parent->files->first) {
parent->files->first =
parent->files->first->next;
} else if (it == parent->files->last) {
parent->files->last = it->prev;
} else {
it->prev->next = it->next;
it->next->prev = it->prev;
}
it = NULL;
free(it);
return;
}
}
if (it == NULL) {
printf("Cannot remove ‘%s’: No such file!\n", dirname);
free(it);
}
}
void rmdir(Directory *parent, char *dirname)
{
NodeDir *it;
for (it = parent->dirs->first; it != NULL; it = it->next) {
if (strcmp(it->newdir->name, dirname) == 0) {
if (it == parent->dirs->first) {
parent->dirs->first =
parent->dirs->first->next;
} else if (it == parent->dirs->last) {
parent->dirs->last =
parent->dirs->last->prev;
} else {
it->prev->next = it->next;
it->next->prev = it->prev;
}
it = NULL;
free(it);
return;
}
}
if (it == NULL) {
printf("Cannot remove ‘%s’: No such directory!\n", dirname);
free(it);
}
}
#endif
/* __FILE_H__ */
Valgrind output:
> create fs ls
>
> ls
>
> mkdir test ls
> ==11466== Conditional jump or move depends on uninitialised value(s)
> ==11466== at 0x109025: ls (file.h:189)
> ==11466== by 0x1097D4: main (main.c:86)
> ==11466== Uninitialised value was created by a heap allocation
> ==11466== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
> ==11466== by 0x108D44: mkdir (file.h:134)
> ==11466== by 0x109766: main (main.c:81)
In touch you missed to set to NULL the fields next and rev
In mkdir you missed to set to NULL the fields files and dirs, and sometimes next
To simplify your code and makes it robust I encourage you to add for each struct a constructor doing the malloc and initializing all the fields including with NULL when the value is not yet known, and also add a destructor for each to free all allocated element. Of course in your case you can also use calloc rather than malloc to put all to 0
deleteroot does not free memory because you set root to NULL before to call free, and because you do not follow the links to free linked resources.
In rmdir you have the same unexpected assignment to NULL before to call free inside the for. At the end if is useless to check if it is NULL because the continuation test of the for is it != NULL, and the free in the last block is useless
Out of the memory leaks because you never free the resources you also introduce memory leaks in mkdir doing
parent->dirs->first = (NodeDir *) malloc(sizeof(NodeDir));
parent->dirs->last = (NodeDir *) malloc(sizeof(NodeDir));
parent->dirs->first = new;
parent->dirs->last = new;
the two first lines must be removed
In
new->newdir = (Directory *) malloc(strlen(Directory) + 1);
strlen(Directory) is invalid, must be
new->newdir = (Directory *) malloc(sizeof(Directory));
In pwd you do
if (dir->parentDir == NULL)
return;
if (dir->parentDir != NULL) {
in that the two first lines are useless
Furthermore you print nothing in case of root, can be :
void pwd(Directory *dir)
{
if (dir->parentDir != NULL) {
pwd(dir->parentDir);
printf("%s/", dir->name);
}
else
putchar('/');
}
In cd the call to free must be removed
In case of .. if there is a parent you will always indicate an error because you consider the sub dirs. Note that at the root level a cd .. does nothing, so replace
if (strcmp(where, "..") == 0 && dir->parentDir != NULL) {
return dir->parentDir;
} else if (dir->dirs == NULL)
by
if (strcmp(where, "..") == 0) {
return (dir->parentDir != NULL) ? dir->parentDir : dir;
} else if (dir->dirs == NULL)
I encourage you to rename the field newfile to file and newdir to dir because the new has no reason
In tree the call to free must be removed
Visibly all is in a header file, I encourage you to put only the struct definitions and function declaration in the header file, and to move the function definitions in a source file, else if you #include several times your header file you will have functions multiply defined

Generalized Linked List: Adding Child Link whenever an opening bracket occurs

Here is my code for generating a GLL for the string input: a,(b,c),d where (b,c) will be linked as a child at the next link of a.
GLL* generateList(char poly[])
{
GLL* newNode = NULL, *first = NULL, *ptr = NULL;
while (poly[i] != '\0')
{
if (poly[i] == ')')
{
return first;
}
else
{
if (poly[i] != ',')
{
if (poly[i] != '(')
{
newNode = createNode(poly[i], 0);
}
else
{
++i;
newNode = createNode('#', 1);
newNode->dlink = generateList(poly);
}
}
}
if (first != NULL)
{
ptr = first;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newNode;
}
else
{
first = newNode;
}
i++;
}
return first;
}
And here is the structure I used for each node.
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
I am not finding a way to add that child link to the parent link whenever the bracket opens. The programs runs in a loop.
Note: I have declared i=0 as a global variable to hold the position of character.
Edit: Here is the createNode function
GLL* createNode(char value, int flag)
{
GLL* newNode;
newNode = (GLL *) malloc(sizeof(GLL)*1);
newNode->data = value;
newNode->dlink = NULL;
newNode->tag = flag;
newNode->next = NULL;
return newNode;
}
How do I do it then?
You could do something like that:
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
GLL* createNode(char value, int flag)
{
GLL* newNode = calloc(1, sizeof(*newNode));
if (!newNode)
return NULL;
newNode->tag = flag;
newNode->data = value;
return newNode;
}
void freeList(GLL *list)
{
for (GLL *current_node = list, *temp; current_node; current_node = temp) {
temp = current_node->next;
freeList(current_node->dlink);
free(current_node);
}
}
GLL* generateList(char *poly, size_t *pos)
{
size_t const length = strlen(poly);
GLL *head = NULL;
GLL *tail = NULL;
for (; *pos < length; ++*pos) {
if (poly[*pos] == '(') {
++*pos; // don't have the next called generateList() read '(' again
tail->dlink = generateList(poly, pos);
if (!tail->dlink) {
freeList(head);
return NULL;
}
continue;
}
else if (poly[*pos] == ')') {
return head;
}
else if (isalpha((char unsigned)poly[*pos])) {
if (!head) {
head = tail = createNode(poly[*pos], 0);
}
else {
tail->next = createNode(poly[*pos], 0);
tail = tail->next;
}
continue;
}
else if (poly[*pos] == ',')
continue;
fputs("Format error :(\n\n", stderr);
freeList(head);
return NULL;
}
return head;
}
void printList(GLL *list)
{
for (GLL *node = list; node; node = node->next) {
printf("%c ", node->data);
if (node->dlink) {
putchar('(');
printList(node->dlink);
printf("\b) ");
}
}
}
int main(void)
{
size_t pos = 0;
GLL *list = generateList("a,(b,(c,d,e(f)),g,h),i,j,k", &pos);
printList(list);
putchar('\n');
freeList(list);
}
Output
a (b (c d e (f)) g h) i j k
Also, if flag is true then it means that the data is not to be considered but there is a child list to be linked.
Sorry, but I don't get how there could be a child list if there is no data for the node.

Trying to delete all the elements from HashTable with the status marked as closed

#include<iostream>
using namespace std;
enum Stare {DESCHIS=10, LUCRU=20, DUPLICAT=30, REZOLVAT=40, INCHIS=50};
struct Task
{
char *idTask;
char *data;
char *numeInginer;
int nivelComplexitate;
Stare stare;
};
struct List
{
Task *task;
List*next;
};
struct HashTable
{
List** vector;
int size;
};
List* creareNodLista(Task *task)
{
List*nod = (List*)malloc(sizeof(List));
nod->task = task;
nod->next = NULL;
return nod;
}
void initHashTable(HashTable &hTable, int size)
{
hTable.vector = (List**)malloc(sizeof(List*)*size);
hTable.size = size;
memset(hTable.vector, 0, sizeof(List*)*size);
}
int fhash(char c, int l)
{
return c%l;
}
void inserareNodLista(List*&list, List*nod)
{
nod->next = list;
list = nod;
}
void inserareNodHashTable(HashTable hTable, List*nod)
{ //determinarea pozitiei pe care se face inserarea
int index = fhash(nod->task->numeInginer[0],hTable.size);
//obtinerea listei in care se face inserarea
List*list = hTable.vector[index];
//inserare element nou in lista
inserareNodLista(list, nod);
//actualizare element in hashTable
hTable.vector[index] = list;
}
List* getHashTable(HashTable ht, char cheie)
{
int f = fhash(cheie, ht.size);
return ht.vector[f];
}
void printHashTable(HashTable ht)
{
for (char c = 'A'; c < 'Z'; c++)
{
List*lista = getHashTable(ht, c);
int count = 0;
while (lista)
{
count++;
printf("%d", count);
printf("%s\n", lista->task->idTask);
printf("%s\n", lista->task->data);
printf("%s\n", lista->task->numeInginer);
printf("%d\n", lista->task->nivelComplexitate);
printf("%d\n", lista->task->stare);
lista = lista->next;
}
if (count>1)
printf("\nColiziune\n\n");
}
}
int stergeNodHashTable(HashTable hTable, char*numeInginer)
{
int pozitie = 0;
pozitie = fhash(numeInginer[0], hTable.size);
if (hTable.vector[pozitie] == NULL)
return -1;
else
{
if (strcmp(hTable.vector[pozitie]->task->numeInginer, numeInginer) == 0)
{
if (hTable.vector[pozitie]->next == NULL)
{
free(hTable.vector[pozitie]->task->idTask);
free(hTable.vector[pozitie]->task->data);
free(hTable.vector[pozitie]->task->numeInginer);
free(hTable.vector[pozitie]->task);
free(hTable.vector[pozitie]);
hTable.vector[pozitie] = NULL;
}
else
{
List*lista = hTable.vector[pozitie];
hTable.vector[pozitie] = lista->next;
free(lista->task->idTask);
free(lista->task->data);
free(lista->task->numeInginer);
free(lista->task);
free(lista);
lista->next = NULL;
lista = NULL;
}
}
else
{
List*tmp = hTable.vector[pozitie];
while (tmp->next != NULL && strcmp(tmp->next->task->numeInginer, numeInginer) != 0)
tmp = tmp->next;
List*list = tmp->next;
if (list->next == NULL)
{
free(list->task->idTask);
free(list->task->numeInginer);
free(list->task->data);
free(list->task);
free(list);
tmp->next = NULL;
list = NULL;
}
else
{
List*tmp = list;
list = list->next;
free(tmp->task->idTask);
free(tmp->task->data);
free(tmp->task->numeInginer);
free(tmp->task);
free(tmp);
tmp->next = NULL;
tmp = NULL;
}
}
}
return pozitie;
}
void main()
{
FILE *pFile = fopen("Text.txt", "r");
Task *task = NULL;
HashTable ht;
initHashTable(ht, 29);
if (pFile)
{
while (!feof(pFile))
{
task = (Task*)malloc(sizeof(Task));
char id[50];
fscanf(pFile, "%s", &id);
task->idTask = (char*)malloc(strlen(id) + 1);
strcpy(task->idTask, id);
char data[50];
fscanf(pFile, "%s", data);
task->data = (char*)malloc(strlen(data) + 1);
strcpy(task->data, data);
char numeInfiner[50];
fscanf(pFile, "%s", numeInfiner);
task->numeInginer = (char*)malloc(strlen(numeInfiner) + 1);
strcpy(task->numeInginer, numeInfiner);
fscanf(pFile, "%d", &task->nivelComplexitate);
fscanf(pFile, "%d", &task->stare);
//creare element lista
List*nod = creareNodLista(task);
//inserare element in hashTable
inserareNodHashTable(ht, nod);
}
fclose(pFile);
for (char c = 'A'; c < 'Z'; c++)
{
List *lista = getHashTable(ht, c);
while (lista)
{
if (lista->task->stare == 50)
stergeNodHashTable(ht, lista->task->numeInginer);
}
}
printHashTable(ht);
}
}
I am trying to delete from hashTable all the elements with status marked as closed. The delete function is working fine but when i call it for al the hashtable, it got me error: lista->task was 0xDDDDDD. I cant understand why. Please help me!

Binary tree not adding strings from file

#include <stdio.h>
#include <stdlib.h>
struct treeNode
{
char *word;
int NumberCnt;
struct treeNode *rightPTR, *leftPTR;
};
typedef struct treeNode node;
node *rootPTR = NULL;
void freeTree(node *currPTR)
{
if (currPTR!= NULL)
{
freeTree(currPTR -> leftPTR);
free(currPTR);
freeTree(currPTR -> rightPTR);
}
}
void printTree(node *currPTR)
{
if (currPTR != NULL)
{
printTree(currPTR ->leftPTR);
printf("%s appeared:%d times\n", currPTR->word, currPTR->NumberCnt);
printTree(currPTR ->rightPTR);
}
}
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
tempPTR -> NumberCnt=0;
tempPTR -> leftPTR = NULL;
tempPTR -> rightPTR = NULL;
if (rootPTR == NULL)
{
rootPTR = tempPTR;
rootPTR -> NumberCnt++;
}
else
{
node *currPTR = rootPTR;
node *prevPTR = NULL;
while (currPTR != NULL)
{
int comp = strcmp(input, (currPTR->word));
if (comp == 0)
{
printf ("Entry already exists\n");
currPTR->NumberCnt++;
return 1;
}
else if (comp < 0)
{
prevPTR = currPTR;
currPTR = currPTR->leftPTR;
}
else if (comp > 0)
{
prevPTR = currPTR;
currPTR = currPTR->rightPTR;
}
}
int comp = strcmp(input, (prevPTR ->word));
if (comp < 0)
{
prevPTR->leftPTR = tempPTR;
prevPTR ->NumberCnt++;
}
else if (comp > 0)
{
prevPTR->rightPTR = tempPTR;
prevPTR->NumberCnt++;
}
return 0;
}
printf("root1%s\n",rootPTR->word);
return 2;
}
int search(char* input)
{
if (input == rootPTR ->word)
{
printf("Node found %s\n", rootPTR->word);
return 0;
}
else
{
if (input < rootPTR ->word)
{
node *currPTR = rootPTR->leftPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR -> rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
if (input > rootPTR ->word)
{
node *currPTR = rootPTR->rightPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf ("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR ->rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
}
return 2;
}
void fixWord(char* buff)
{
char* unfixed = buff;
char* fixed = buff;
while (*unfixed)
{
if (isalpha(*unfixed))
{
*fixed=tolower(*unfixed);
*fixed++;
}
*unfixed++;
}
*fixed=0;
}
int main()
{
FILE *ptr_file;
char buff [100];
//ptr_file = fopen ("sherlock.txt", "r");
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff ) != EOF)
{
int comparison = strcmp(buff, "endoffile");
if (comparison == 0)
{
return 0;
}
fixWord(buff);
insertNode(buff);
}
fclose(ptr_file);
printf("root:%s\n", rootPTR->word);
return 0;
}
Ok I have this binary tree which is taking string inputs from a file. It works if I pass strings directly to the tree, however when I attempt to pass it the strings I read in form the file it keeps on replacing the root node and does not add them correctly to the tree.
buff is current line value and overwritten on each line reading:
insertNode(buff);
insertNode assigns overwriten buffer.
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
....
So, you should dynamic allocation for input value as:
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = strdup(input);
....
You're passing buff to your insert function, and it's storing that in the node. So all your nodes will end up pointing to the same address, that of buff in main.
You need to allocate storage for each string in each node, and copy your input into that. And remember to deallocate properly when you delete your tree.
strdup can be handy for that if your library has it.

Resources