I do not know why this is not working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// struct of list
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} * liste;
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void initialisation(liste* LBO)
{
*LBO = NULL;
}
I think it's here the problem when I create q (q is created to point to the previous node).
void creation(liste* LBO)
{
liste q, prec = NULL;
int i = 0;
srand(time(NULL));
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(liste));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(liste LBO)
{
printf("\nvoici ta liste \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
if (LBO == NULL)
printf("NULL");
}
int main()
{
// or here
printf("Hello world!\n");
liste LBO;
initialisation(&LBO);
creation(&LBO);
affichage(LBO);
return 0;
}
There are several issues:
Instead of calling
initialisation(&LBO);
which is not really wrong, just write:
LBO = NULL;
Then don't hide pointers with typedefs, it only adds confusion.
Instead of:
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} *liste;
Write:
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
and use struct noeud* instead of liste.
Now the real problem:
This is wrong. Here you allocate the size for a pointer, but you need to allocate the size for the whole structure:
q = malloc(sizeof(liste));
which is actually the same as:
q = malloc(sizeof(struct noeud*))
but you need:
q = malloc(sizeof(struct noeud))
You see now why hiding pointers with typedefs is a bad idea.
So here is the corrected version of your program (#includes ommitted for brevity):
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void creation(struct noeud** LBO)
{
struct noeud* q, *prec = NULL;
int i = 0;
// srand(time(NULL)); <<<<< don't call srand here, call it once at the
// beginning of the program
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(struct noeud));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(struct noeud* LBO)
{
printf("\nvoici ta struct noeud* \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
// if (LBO == NULL) <<<<<<<<<<< drop this, LBO is always NULL here
// but it doesn't hurt, it's just useless
printf("NULL");
}
int main()
{
srand(time(NULL)); // <<<<<<<<<<<<< call srand here
struct noeud* LBO;
LBO = NULL;
creation(&LBO);
affichage(LBO);
return 0;
}
There is still room for improvement, especially the creation function is somewhat awkward.
Also look at the comments with <<<<<<<<<<<, there are minor corrections
Related
My problem is that this code is not working in VS 2017 while in CLion it works.
VS says:
Severity Code Description Project File Line Suppression State
Error (active) E0144
a value of type void * cannot be used to initialize an entity of type queue_t*
therefor the program is not allocating the memory.
Further every pointer like the example above is not working.
Does somebody here know why that is the case, why VS thinks that this would be a void?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
struct packet_t {
double d;
int i;
long l;
char *p;
struct queue_t *queue;
};
struct queue_t {
char *name;
int size;
int entries;
double time;
struct packet_t **packets;
int read;
int write;
long lost;
long total;
};
int decision = -1;
int isRunning = 1;
void logError(char message[]) {
printf("ERROR: %s", message);
}
struct queue_t *queue_create(char *name, int size) {
struct queue_t *q = malloc(sizeof(struct queue_t));
if (!q) {
logError("could not allocate memory!\n");
return 0;
}
else {
q->name = name;
q->size = size;
q->entries = 0;
q->read = 0;
q->write = 0;
q->total = 0;
q->lost = 0;
q->packets = malloc(size * sizeof(struct packet_t *));
if (!q->packets) {
logError("could not allocate memory!\n");
free(q);
return 0;
}
struct packet_t **current;
for (int i = 0; i < size; i++) {
current = q->packets + i;
*current = NULL;
}
}
return q;
}
int packet_destroy(struct packet_t *packet) {
//TODO test if deleted ?
if (packet) {
free(packet);
return 1;
}
return 0;
}
long queue_store(struct queue_t *queue, struct packet_t *packet) {
if (queue->entries < queue->size) {
packet->queue = queue;
*(queue->packets + queue->write) = packet;
queue->write++;
if (queue->write == queue->size) {
queue->write = 0;
}
queue->total++;
queue->entries++;
return queue->total;
}
//cant save packet ->destroy
packet_destroy(packet);
queue->lost++;
return 0;
}
struct packet_t *queue_retrieve(struct queue_t *queue) {
if (queue->entries == 0) return NULL;
struct packet_t **current = queue->packets + queue->read;
struct packet_t *packet = *current;
*current = NULL;
if (packet->queue) {
packet->queue = NULL;
}
queue->entries--;
queue->read++;
if (queue->read == queue->size) {
queue->read = 0;
}
return packet;
}
struct packet_t *packet_create(int i, double d, long l, char *p) {
struct packet_t *new = malloc(sizeof(struct packet_t));
if (new) {
new->i = i;
new->d = d;
new->l = l;
new->p = p;
}
else {
logError("failed to allocate memory");
}
return new;
}
int queue_destroy(struct queue_t *queue) {
if (!queue) {
logError("could not find queue!");
return 0;
}
struct packet_t *p;
for (int i = 0; i < queue->size; i++) {
p = *(queue->packets + i);
packet_destroy(p);
}
//TODO test if not needed as it's already free'd in packet_destroy
free(queue->packets);
free(queue);
return 0;
}
long test_queue(int val) {
int sum = 0, finalTime = 0;
clock_t startTime, finalTicks;
startTime = clock();
while (finalTime < val) {
struct queue_t *q = queue_create("test", 10);
queue_destroy(
sum++;
finalTicks = (clock() - startTime);
// printf("ticks: %d\n", finalTicks);
finalTime = (int)floor((finalTicks / (double)CLOCKS_PER_SEC));
// printf("time: %d\n", finalTime);
}
printf("Runtime: %d\n seconds", finalTime);
printf("Added and removed %d queues\n", sum);
}
long test_packets(int val) {
int finalTime = 0;
struct queue_t *q = queue_create("test", 10);
clock_t startTime, finalTicks;
startTime = clock();
while (finalTime < val) {
struct packet_t *t = packet_create(finalTime, finalTime + 1, finalTime + 2, NULL);
queue_store(q, t);
packet_destroy(queue_retrieve(q));
finalTicks = (clock() - startTime);
// printf("ticks: %d\n", finalTicks);
finalTime = (int)floor((finalTicks / (double)CLOCKS_PER_SEC));
// printf("time: %d\n", finalTime);
}
printf("Runtime: %d\n", finalTime);
printf("Successfully added %li entries\n", q->total);
printf("Failed to add %li entries\n", q->lost);
queue_destroy(q);
}
void resetDecision() {
decision = -1;
isRunning = 1;
}
void checkDecision() {
while (decision != 0 && decision != 1 && decision != 2) {
printf("Select option:\n (1) Run queue test \n (2) Run packet test \n(0) to cancel \n");
scanf("%d", &decision);
}
if (decision == 0) {
isRunning = 0;
}
else if (decision == 1) {
int val = 0;
while (val <= 0) {
printf("Enter the time to test");
scanf("%d", &val);
}
printf("Running test for %d seconds....\n", val);
test_queue(val);
}
else if (decision == 2) {
int val = 0;
while (val <= 0) {
printf("Enter the time to test");
scanf("%d", &val);
}
printf("Running test for %d seconds....\n", val);
test_packets(val);
}
if (decision != 0)
resetDecision();
}
int main() {
while (isRunning) {
checkDecision();
}
return 0;
}
You are compiling your program as a C++ program. In C++ there is no implicit conversion from the type void * to pointer of other object type.
So you need to write using explicit casting like
struct queue_t *q = ( struct queue_t * )malloc(sizeof(struct queue_t));
Or you should consider your program as indeed a C++ program and use the operator new instead of the C function malloc.
#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!
I have a program in C which reads definition of graph from file, search for Hamiltonian cycle (only one) and prints it on screen if found. Problem is that program is crashing when I'm trying to find cycle in graphs with 30 and more vertices (for 30 vertices it sometimes shows cycle end get crashed (with different saturations), for more get crashed instantly). When I try to debug it stops at free() function and shows SIGTRAP signal. What can I do to fix that? Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
typedef struct Lista
{
struct Lista * next;
int v;
} Lista;
Lista * stos;
bool *visited;
int wierzcholki, krawedzie;
int *S;
int sptr;
Lista **graf;
bool czyZnaleziono = false;
int DFSHamilton(int v)
{
if (!czyZnaleziono)
{
int i;
bool test;
Lista *p;
S[sptr++] = v;
if(sptr < wierzcholki)
{
visited[v] = true;
for(p = graf[v]; p; p = p->next)
if(!visited[p->v]) DFSHamilton(p->v);
visited[v] = false;
}
else
{
test = false;
for(p = graf[v]; p; p = p->next)
if(!(p->v))
{
test = true;
break;
}
if(test)
{
printf("Hamiltonian Cycle : ");
for(i = 0; i < sptr; i++)
{
printf("%d ",S[i]);
}
printf("0\n");
czyZnaleziono = true;
}
}
sptr--;
}
}
int main()
{
FILE *plik;
Lista *p, *r;
plik = fopen("rzeczy40-95.txt", "r");
double start, stop, czas;
int i, j, w1, w2;
sptr = 0;
visited = malloc(krawedzie*sizeof(bool));
if (plik == NULL)
{
printf("Nie mozna odnalezc pliku");
return 0;
}
else
{
fscanf(plik, "%d %d", &wierzcholki, &krawedzie);
S = malloc(wierzcholki*sizeof(int));
graf = malloc(wierzcholki*sizeof(Lista));
for(i=0; i<wierzcholki; i++)
{
graf[i] = NULL;
visited[i] = false;
}
for(j=0; j<krawedzie; j++)
{
fscanf(plik,"%d %d", &w1, &w2);
p = malloc(sizeof(Lista));
r = malloc(sizeof(Lista));
p->v = w2;
p->next = graf[w1];
graf[w1] = p;
r->v = w1;
r->next = graf[w2];
graf[w2] = r;
}
fclose(plik);
DFSHamilton(0);
free(visited);
free(S);
for (i = 0; i < wierzcholki; i++)
{
free(graf[i]);
}
free(graf);
return 0;
}
}
I enter several numbers(2,1,4,5,9,3,6,7),after I enter the number '3', there something wrong,the function can not return correctly.
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode
{
int data;
int height;
struct AVLNode *LChild;
struct AVLNode *RChild;
}*AVLTree;
typedef struct AVLNode *Position;
static int Height(Position T)
{
if (T == NULL)
return -1;
else
return T->height;
}
static Position SingleLeft(Position k2)
{
Position k1;
k1 = k2->LChild;
k2->LChild = k1->RChild;
k1->RChild = k2;
k2->height = max(Height(k2->LChild), Height(k2->RChild)) + 1;
k1->height = max(Height(k1->LChild), Height(k1->RChild)) + 1;
return k1;
}
static Position SingleRight(Position k1)
{
Position k2;
k2 = k1->RChild;
k1->RChild = k2->LChild;
k2->LChild = k1;
k1->height = max(Height(k1->LChild), Height(k1->RChild)) + 1;
k2->height = max(Height(k2->LChild), Height(k2->RChild)) + 1;
return k2;
}
static Position DoubleLeft(Position k3)
{
k3->LChild = SingleRight(k3->LChild);
return SingleLeft(k3);
}
static Position DoubleRight(Position k1)
{
k1->RChild = SingleLeft(k1->RChild);
return SingleRight(k1);
}
void PrePrint(AVLTree T)
{
if (T != NULL)
{
printf("%d ", T->data);
PrePrint(T->LChild);
PrePrint(T->RChild);
}
}
AVLTree Insert(int x, AVLTree T)
{
if (T == NULL)
{
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->data = x;
T->LChild = T->RChild = NULL;
}
else if (x < T->data)
{
T->LChild = Insert(x, T->LChild);
if (Height(T->LChild) - Height(T->RChild) == 2)
{
if (x<T->LChild->data)
T = SingleLeft(T);
else
T = DoubleLeft(T);
}
}
else if (x > T->data)
{
T->RChild = Insert(x, T->RChild);
if (Height(T->RChild) - Height(T->LChild) == 2)
{
if (x>T->RChild->data)
T = SingleRight(T);
else
T = DoubleRight(T);
}
}
T->height = max(Height(T->LChild), Height(T->RChild)) + 1;
return T;
}
I think there is something wrong in my main function, I think I shouldn't write
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->LChild = T->RChild = NULL;
those code in mian function, I try to add a 'Init' function, but it doesn't work. It always said "'T' is being used without initialized"
int main()
{
AVLTree T;
T=(AVLTree)malloc(sizeof(struct AVLNode));I think there is wrong
T->LChild = T->RChild = NULL;
int x;
printf("please enter the data(0 to quit):");
scanf("%d", &x);
T->data = x;
while (x != 0)
{
Insert(x, T);
printf("enter a number(0 to quit):");
scanf("%d", &x);
}
PrePrint(T);
}
When your insertion makes a new root node, this fact is not propagated back to main in any way. The value of T inside the Insert function changes, but main has its own variable called T that isn't changed, and that's the one that you then use to print out the tree.
I notice that your Insert function returns an AVLTree, but when main calls it it doesn't do anything with the return value.
(This is not the only thing that's amiss in your code, but it would be a good place to start.)
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
typedef struct pr_struct{
int owner;
int burst_time;
struct pr_struct *next_prcmd;
} prcmd_t;
static prcmd_t *pr_head = NULL;
static prcmd_t *pr_tail = NULL;
static int pending_request = 0;
static pthread_mutex_t prmutex = PTHREAD_MUTEX_INITIALIZER;
int add_queue(prcmd_t *node)
{
pthread_mutex_lock(&prmutex);
//code
prcmd_t *curNode = pr_head;
if(pr_head == NULL) { pr_head = node; return;}
while(curNode->next_prcmd)
{
curNode->next_prcmd = (prcmd_t*)malloc(sizeof(prcmd_t));
curNode = curNode->next_prcmd;
}
curNode->next_prcmd = node;
//
pending_request++;
pthread_mutex_unlock(&prmutex);
return(0);
}
int main()
{
if (pr_head == NULL)
{
printf("List is empty!\n");
}
prcmd_t *pr1;
pr1->owner = 1;
pr1->burst_time = 10;
add_queue(pr1);
prcmd_t *curNode = pr_head;
while(curNode->next_prcmd)
{
printf("%i\n", curNode->owner);
curNode = curNode->next_prcmd;
}
}
EDIT:
Here's what I have now...
int main()
{
prcmd_t *pr1;
pr1 = (prcmd_t*)malloc(sizeof(prcmd_t));
pr1->owner = 1;
pr1->burst_time = 10;
if (pr_head == NULL)
{
printf("List is empty!\n");
}
add_queue(pr1);
prcmd_t *curNode = pr_head;
printf("made it here 1\n");
while(curNode->next_prcmd)
{
printf("in the while loop\n");
printf("%i\n", curNode->owner);
curNode = curNode->next_prcmd;
}
}
output is:
List is empty!
made it here 1
pr1 is an uninitialized pointer to prcmd_t struct, dereferencing uninitialized pointer causes undefined behavior.
You need to allocate space for the structure on the heap / stack (depending on where it's gonna be used), so one option is:
// Allocate on stack
prcmd_t pr1;
pr1.owner = 1;
pr1.burst_time = 10;
add_queue(&pr1);
and second is:
//Allocae on heap
prcmd_t *pr1;
pr = (prcmd_t*)malloc(sizeof(prcmd_t));
pr1->owner = 1;
pr1->burst_time = 10;
add_queue(pr1);
Modifying your main method (and main only) to:
int main()
{
if (pr_head == NULL)
{
printf("List is empty!\n");
}
prcmd_t *pr1;
pr1 = (prcmd_t*)malloc(sizeof(prcmd_t));
pr1->owner = 1;
pr1->burst_time = 10;
add_queue(pr1);
prcmd_t *curNode = pr_head;
while(curNode && curNode->owner)
{
printf("%i\n", curNode->owner);
curNode = curNode->next_prcmd;
}
}
Outputs
List is empty!
1
It's hard to tell without you tellung us where...
But
you have to initialize
node->next_prcmd to null
why do you malloc in the while loop? you are
thereby destroing your current->next,
which in the next iteration is pretty
bad...
Mario