List of lists C - c

I want to make list made of lists and the inner list is made of items.
Union of datatype:
typedef union s_datatype {
int t_int;
char* t_char;
double t_double;
bool t_bool;
} t_datatype;
Structure of item:
typedef struct s_token {
int y;
int type;
t_datatype value;
struct s_token *next;
} t_token;
Structure of inner list:
typedef struct s_line {
int x;
int depth;
int type;
int number_of_tokens;
t_token*head;
struct s_line *next;
} t_line;
Structure of the final list:
typedef struct s_tokenized_code {
int number_of_lines;
t_line*head;
} t_tokenized_code;
Let's say that I want to add new "line" and into that line, I want to insert the "token". But I don't know, how to put this together. Can you help me? I'm not sure how to alloc this and how to work with this list of lists.
EDIT: Structure modified

Solved.
If you want to know, how to (i want to insert items to the end of list, not beginning):
t_token*init_token (int y, int type, t_datatype value) {
t_token*token = malloc(sizeof(struct s_token));
if (token == NULL) {
return NULL;
}
token->y = y;
token->type = type;
token->value = value;
token->next = NULL;
return token;
}
t_line*init_line (int x, int depth, int type) {
t_line*line = malloc(sizeof(struct s_line));
if (line == NULL) {
return NULL;
}
line->x = x;
line->depth = depth;
line->type = type;
line->number_of_tokens = 0;
line->head = NULL;
line->next = NULL;
return line;
}
t_tokenized_code*init_code (void) {
t_tokenized_code*code = malloc(sizeof(struct s_tokenized_code));
if (code == NULL) {
return NULL;
}
code->number_of_lines = 0;
code->head = NULL;
return code;
}
void insert_token (t_line*line, t_token*token) {
if (token != NULL) {
if (line->head == NULL){
line->head = token;
line->number_of_tokens += 1;
return;
}
t_token*tmp = line->head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = token;
line->number_of_tokens += 1;
}
}
void insert_line (t_tokenized_code*code, t_line*line) {
if (line != NULL) {
if (code->head == NULL) {
code->head = line;
code->number_of_lines += 1;
return;
}
t_line*tmp = code->head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = line;
code->number_of_lines += 1;
}
}
void free_code (t_tokenized_code*source) {
if (source == NULL) {
return;
}
t_line*line;
t_token*token;
while ((line = source->head) != NULL) {
while ((token = line->head) != NULL) {
line->head = token->next;
free(token);
}
source->head = line->next;
free(line);
}
free(source);
}
Let's make a simple test - Adding 2 tokens to the first line and 3 tokens to the second line:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main (void) {
t_tokenized_code*source = init_code();
t_line*line = init_line(0,0,3);
if (line == NULL) {
return 1;
}
insert_line(source, line);
t_datatype tt;
tt.t_char = "first";
t_token*token = init_token(0,6, tt);
if (token == NULL) {
return 1;
}
insert_token(line, token);
tt.t_char = "second";
token = init_token(1,6, tt);
insert_token(line, token);
line = init_line(1,0,3);
insert_line(source, line);
tt.t_char = "third";
token = init_token(0,6, tt);
insert_token(line, token);
tt.t_char = "fourth";
token = init_token(1,6, tt);
insert_token(line, token);
tt.t_char = "fifth";
token = init_token(2,6, tt);
insert_token(line, token);
line = source->head;
while (line != NULL) {
printf("****\n");
token = line->head;
while (token != NULL) {
printf("%s\n", token->value.t_char);
token = token->next;
}
line = line->next;
}
free_code (source);
return 0;
}
The output will be following:
****
first
second
****
third
fourth
fifth

Related

Cant insert Node to binary tree

I am trying to insert Node to Binary tree. This is my function for creating Node (rest is done).
void BVSCreate_function(TNodef *rootPtr, function_save token) {
TNodef *newPtr = malloc(sizeof(struct tnodef));
if (newPtr == NULL) {
fprintf(stderr, "99");
return;
}
TNodef init;
string initStr;
initStr.str = NULL;
initStr.length = 0;
initStr.alloc = 0;
newPtr = &init;
newPtr->content = &initStr;
newPtr->leftPtr = NULL;
newPtr->rightPtr = NULL;
newPtr->return_type = token.ret_value;
newPtr->parameters = token.param_count;
strCpyStr(newPtr->content, token.content);
rootPtr = newPtr;
}
void BVSInsert_function(TNodef *rootPtr, function_save token) {
if (rootPtr == NULL) {
BVSCreate_function(rootPtr, token);
} else {
if ((strCmpStr(token.content, rootPtr->content)) < 0) {
BVSCreate_function(rootPtr->leftPtr, token);
} else
if ((strCmpStr(token.content, rootPtr->content)) > 0) {
BVSCreate_function(rootPtr->rightPtr, token);
}
}
}
When TNodef and function_save are structs:
typedef struct {
string *content;
int param_count;
int ret_value;
} function_save;
typedef struct tnodef {
string *content;
struct tnodef *leftPtr;
struct tnodef *rightPtr;
int parameters;
int return_type;
} TNodef;
Where string is defined as this struct:
typedef struct {
char *str; // content of string
int length; // length of string
int alloc; // amount of memory allocated
} string;
strCpystr function :
int strCpyStr(string *s1, string *s2) {
int len2 = s2->length;
if (len2 > s1->alloc) {
if (((s1->str) = (char *)realloc(s1->str, len2 + 1)) == NULL) {
return 1;
}
s1->alloc = len2 + 1;
}
strcpy(s1->str, s2->str);
s1->length = len2 + 1;
return 0;
}
I am trying to create a node in binary tree and put there information from struct function_save.
But when I try to print this tree after insert it shows me that tree is still empty.
Your code in BVSCreate_function has undefined behavior because:
newPtr = &init; discards the allocated node and instead uses a local structure that will become invalid as soon as the function returns.
newPtr->content = &initStr; is incorrect for the same reason: you should allocate memory for the string too or possibly modify the TNodeDef to make content a string object instead of a pointer.
Function BVSInsert_function does not return the updated root pointer, hence the caller's root node is never updated. You could change the API, passing the address of the pointer to be updated.
There is also a confusion in BVSInsert_function: it should call itself recursively when walking down the tree instead of calling BVSCreate_function.
Here is a modified version:
/* Allocate the node and return 1 if successful, -1 on failure */
int BVSCreate_function(TNodef **rootPtr, function_save token) {
TNodef *newPtr = malloc(sizeof(*newPtr));
string *newStr = malloc(sizeof(*content));
if (newPtr == NULL || newStr == NULL) {
fprintf(stderr, "99");
free(newPtr);
free(newStr);
return -1;
}
newStr->str = NULL;
newStr->length = 0;
newStr->alloc = 0;
newPtr->content = newStr;
newPtr->leftPtr = NULL;
newPtr->rightPtr = NULL;
newPtr->return_type = token.ret_value;
newPtr->parameters = token.param_count;
strCpyStr(newPtr->content, token.content);
*rootPtr = newPtr;
return 1;
}
int BVSInsert_function(TNodef **rootPtr, function_save token) {
if (*rootPtr == NULL) {
return BVSCreate_function(rootPtr, token);
} else {
if (strCmpStr(token.content, rootPtr->content) < 0) {
return BVSInsert_function(&rootPtr->leftPtr, token);
} else
if ((strCmpStr(token.content, rootPtr->content)) > 0) {
return BVSInsert_function(&rootPtr->rightPtr, token);
} else {
/* function is already present: return 0 */
return 0;
}
}
}
Note also that function strCpyStr may write beyond the end of the allocated area is len2 == s1->alloc, assuming s1->len is the length of the string, excluding the null terminator.
Here is a modified version:
int strCpyStr(string *s1, const string *s2) {
int len2 = s2->length;
if (len2 >= s1->alloc) {
char *newstr = (char *)realloc(s1->str, len2 + 1);
if (newstr == NULL) {
return 1;
}
s1->str = newstr;
s1->alloc = len2 + 1;
}
strcpy(s1->str, s2->str);
s1->length = len2;
return 0;
}

Heap buffer overflow on a getline() - C

I am coding a local server, I need to parse a file to get the config of the server.
Problem : I have a heap buffer overflow indicated at on the while.
This probeme is shown when I run with -fsanitize but I don't have any trouble without.
Here is the code :
struct container *configParse(FILE *file)
{
char *line = NULL;
size_t n;
char *token = NULL;
char *saveptr = NULL;
struct container *head = NULL;
struct container *container = NULL;
int key = 0;
int first = 1;
while ((getline(&line, &n, file)) != -1)
{
token = strtok_r(saveptr, " =\n\r", &line);
while (token != NULL)
{
if (token[0] == '[')
{
if (first)
{
container = container_init();
container->title = token;
head = container;
first = 0;
}
else
{
container = container_add_back(container);
container = container->next;
container->item = NULL;
container->title = token;
}
key = 0;
}
else
{
if (key == 0)
{
if (container->item == NULL)
{
container->item = items_init();
container->item->key = token;
}
else
{
struct item *itemcpy = container->item;
while (itemcpy->next != NULL)
{
itemcpy = itemcpy->next;
}
itemcpy->next = items_init();
itemcpy->next->key = token;
}
key = 1;
}
else
{
struct item *itemcpy = container->item;
while (itemcpy->next != NULL)
{
itemcpy = itemcpy->next;
}
itemcpy->value = token;
key = 0;
}
}
token = strtok_r(NULL, " =\n\r", &line);
}
}
container_print(head);
printf("\n*****Parsing du .conf*****\n\n");
if (isvalid(head))
printf("Parsing OK\n");
else
{
printf("Parsing KO\n");
return NULL;
}
return head;
}
Thanks in advance.
As explained I try to run the program without -fsanitze, and everything was fine

circular linked list not working properly in c windows

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;
}

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!

Encountering segment fault when printing out directories in Ubuntu

I've been working on this code for a while and I can not figure out the problem. The idea is to print out all directories and sub directories from the given directory (hard coded for testing purposes). However, I keep getting a segmentation fault.
#include <stdio.h>
#include <dirent.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
struct item
{
char location[256];
int level;
int order;
bool isExpanded;
struct item *next;
};
struct item *headNode = NULL;
struct item *currentNode = NULL;
struct item *loopNode = NULL;
static int currentLevel = 1;
static int currentOrder = 1;
bool finished = false;
char currentLocation[256];
void addNode(char location[256])
{
struct item *ptr = (struct item*)malloc(sizeof(struct item));
ptr->level = currentLevel;
ptr->order = currentOrder;
ptr->isExpanded = false;
int x;
for(x = 0; x < strlen(location); x++)
ptr->location[x] = location[x];
ptr->location[x] = '\0';
ptr->next = NULL;
currentNode->next = ptr;
currentNode = ptr;
}
int main(int argc, char *argv[])
{
struct dirent *pDirent;
DIR *pDir;
argv[1] = "/home/collin/Documents";
char temp[256];
pDir = opendir (argv[1]);
if (pDir == NULL)
{
printf ("Cannot open directory '%s'\n", argv[1]);
return 1;
}
closedir (pDir);
headNode = (struct item*)malloc(sizeof(struct item));
headNode->level = currentLevel;
headNode->order = currentOrder;
headNode->isExpanded = false;
int x;
for(x = 0; x < strlen(argv[1]); x++)
{
headNode->location[x] = argv[1][x];
currentLocation[x] = argv[1][x];
}
headNode->location[x] = '\0';
currentLocation[x] = '\0';
headNode->next = NULL;
currentNode = headNode;
while(!finished)
{
finished = true;
loopNode = headNode;
currentLevel++;
currentOrder = 1;
while(loopNode != NULL)
{
if(!loopNode->isExpanded)
{
pDir = opendir (loopNode->location);
for (x = 0; x < strlen(loopNode->location); x++)
{
currentLocation[x] = loopNode->location[x];
}
currentLocation[x] = '\0';
while ((pDirent = readdir(pDir)) != NULL)
{
finished = false;
if(!(!strcmp(pDirent->d_name, ".")||!strcmp(pDirent->d_name, "..")))
{
sprintf(temp, "%s/%s", currentLocation, pDirent->d_name);
addNode(temp);
currentOrder++;
}
}
closedir (pDir);
loopNode->isExpanded = true;
}
loopNode = loopNode->next;
}
}
currentNode = headNode;
while (currentNode != NULL)
{
printf ("%d:%d:%s\n", currentNode->level, currentNode->order, currentNode->location);
currentNode = currentNode->next;
}
return 0;
}
You're not checking that opendir's parameter is a directory, and trying to call it on files too. Either check opendir return value, or check that file you requesting to open is actually a directory, or - even better - both.

Resources