Calling malloc in structure - c

struct NODE{
double theta, phi;
int ID;
int pointer;
};
int main(void)
{
FILE *fp;
int ID[5000][5000];
struct NODE node[5000*5000];
struct NODE node2[5000*5000];
int elem[5000][8];
int tempID;
for(i=0; i< 5000*5000; i++){
node[i].theta = 0;
node[i].phi = 0;
}
for(k=0; k<5000; k++){
for(j=0; j< 5000; j++){
ID[k][j] = -1;
}
}
}
This is a part of the source code of my project. here i want to allocate memory in this lines using malloc. How can i do this??
struct NODE node[5000*5000];
struct NODE node2[5000*5000];

You need to call malloc in the following manner:
struct NODE *node, *node2;
node = malloc(5000*5000*sizeof(*node));
if (node == NULL)
{
exit(1); // or any other error check
}
node2 = malloc(5000*5000*sizeof(*node));
if (node2 == NULL)
{
exit(1); // or any other error check
}
Rest of the code will be unchanged.

Related

Node structure gains itself as a parent during expansion

My assignment is to write a solver for 3x3 sliding tile puzzle which has to embedded later.
I have the structure
struct node
{
char state[9];
struct node* parentNode;
char lastMove;
} node;
I use a pseudo stack for
struct node
{
char state[9];
struct node* parentNode;
char lastMove;
} node;
I use a stack which will be used later for the IDS algorithm.
struct node stack[60000];
struct node* Node = stack;
#define push(Node, n) (*((Node)++) = (n))
#define pop(Node) (*--(Node))
My function expandNode creates all valid child nodes of its given parent
void expandNode(struct node* parent)
{
char help;
int emptyField = -1;
struct node newNode;
for (int i = 0; i < 9; i++)
{
if (parent->state[i] == '0') emptyField = i;
}
for (int i = 0; i < 4; i++)
{
if(lastMoveVal(parent->lastMove, moves[i]) == '0') continue;
if (moveValid(parent->state, moves[i]) == '1')
{
newNode.parentNode = parent;
...
My main function
void main()
{
struct node root;
char rootState[9] = { '6','8','3','0','4','5','1','7','2' };
assignArray(root.state, rootState);
push(Node, root);
struct node curr;
curr = pop(Node);
expandNode(&curr);
for(int i = 0; i < 10; i++)
{
curr = pop(Node);
printf("\n");
for(int j = 0; j<9; j++)
{
printf("%c", curr.state[j]);
};
printf(" PARENT: ");
for(int j = 0; j<9; j++)
{
printf("%c", curr.parentNode->state[j]);
};
}
}
Here is the output:
683405172 PARENT: 683405172
683145072 PARENT: 683145072
083645172 PARENT: 083645172
As you see the expansion of the nodes is correct but the state of the parent node is not the expected 683045172 but the state of node itself.

how to initializing a hash table in C

I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HSZ 127
#define HASHING(x) ((x)%HSZ)
struct node_t{
int val;
struct node_t *next;
};
struct node_t *hash_table[HSZ];
void init(void){
int i;
//memset(hash_table,0,sizeof(hash_table));
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
}
void insert_hash(int value){
int key = HASHING(value);
struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));
newNode->val = value;
newNode->next = NULL;
if(hash_table[key] == NULL){
hash_table[key] = newNode;
} else {
newNode->next = hash_table[key];
hash_table[key] = newNode;
}
}
int delete_hash(int value){
int key = HASHING(value);
if (hash_table[key] == NULL)
return 0;
struct node_t *delNode = NULL;
if (hash_table[key]->val == value){
delNode = hash_table[key];
hash_table[key] = hash_table[key]->next;
} else {
struct node_t *node = &hash_table[key];
struct node_t *next = hash_table[key]->next;
while (next){
if (next->val == value){
node->next = next->next;
delNode = next;
break;
}
node = next;
next = node->next;
}
}
return 1;
free(delNode);
}
void PrintAllHashData()
{
printf("###Print All Hash Data###\n");
for (int i = 0; i < HSZ; i++){
if (hash_table[i] != NULL){
printf("idx : %d ", i);
struct node_t *node = hash_table[i];
while (node->next){
printf("%d ", node->val);
node = node->next;
}
printf("%d\n", node->val);
}
}
}
int main(void){
init();
insert_hash(1);
insert_hash(3);
insert_hash(128);
PrintAllHashData();
}
look at this code.
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.
then, I changed this line to
for(i=0; i<HSZ; i++){
hash_table[i].val = 0;
hash_table[i]->next = NULL;
}
but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'
I think that I don't understand clearly about struct in C.
How to fix this problem?
What you are dealing with is Undefined Behavior.
See, struct node_t *hash_table[HSZ];
So, hash_table is an array of HSZ (127) pointers of the data type struct node_t.
When you do,
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
hash_table[0] to hash_table[126] pointers are not pointing to anything.
So, each of them (or all of them) should be initialized first to point to an object of the type struct node_t and then you can initialize them. For that matter, Using a memset does not cause a problem because memset is filling the contents of the pointers with all zeros. There is difference between filling the pointers with all zeros and filling all zeros to the memory pointed by pointers.
Trying this,
for(i=0; i<HSZ; i++){
hash_table[i].val = 0;
hash_table[i]->next = NULL;
}
is plain wrong.
To fix the issue you are facing, you need to allocate memory dynamically using malloc. You can do the in your for loop.
for(i = 0; i < HSZ; i++)
{
//Allocate memory of the size struct_node_t
hash_table[i] = malloc(sizeof(struct node_t)); //Do not cast!
//Check if memory is allocated
if(hash_table[i] == NULL)
{
//Memory not allocated, set some error state to handle and break
break;
}
//Initialize to zero
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
struct node_t{
int val;
struct node_t *next;
};
struct node_t *hash_table[HSZ];
when you have *hash_table[HSZ], this varible hash_table is a pointer. so whatever your action is , use hash_table-> ,syntax for pointer, mean point to somewhere.
a suggestion that when you use pointer you should always allocate memory hash_table[i] = malloc(sizeof(struct node_t));
struct node_t hash_table;
but if you initilize your varible like this, you can use hash_table.val = 0
so the way of assign value depend on how you declare your varibles
struct node_t *hash_table[HSZ];
gives you an array of pointers that are unset (i.e. not pointing to anything)
void init(void) {
int i;
// memset(hash_table,0,sizeof(hash_table));
for (i = 0; i < HSZ; i++) {
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
tries writing to your invalid pointers which gives undefined behavior.
Either make the array an array of structs (instead of pointers):
struct node_t hash_table[HSZ];
...
/* note use of . instead of -> since we have structs not pointers */
hash_table[i].val = 0;
or allocate the necessary structs so the array points to something:
for (i = 0; i < HSZ; i++) {
hash_table[i] = malloc(sizeof(struct node_t));
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}

Freeing a double pointer from a struct

I have a problem with my delete_table function. So i have 2 structs
struct _entry_ {
int key;
int data;
struct _entry_* next;
struct _entry_* prev;
};
typedef struct _entry_ entry;
struct _table_ {
entry** entries;
int size;
};
typedef struct _table_ table;
I initialise my table with calloc.
void table_init(table* ht, int initial_size) {
ht->entries = (entry**)calloc(initial_size, sizeof(entry*));
if (ht->entries) {
ht->size = initial_size;
}
}
Now my free function that i wrote
void table_destroy(htable* ht) {
entry *el, *temp;
int i;
for(i = 0; i < ht->size; i++) {
el = ht->entries[i];
while(el != NULL){
temp = el;
el = el->next;
free(temp);
}
free(ht->entries[i]);
}
free(ht); // <- don't know do i need this.
}
When i test it with valgrind i got this error
==13560== Invalid free() / delete / delete[] / realloc()
==13560== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13560== by 0x400783: htable_destroy (htable.c:46)
==13560== by 0x400A24: main (main.c:25)
==13560== Address 0xffefffae0 is on thread 1's stack
==13560== in frame #2, created by main (main.c:7)
Any help would be great, thank you for your time!
void table_destroy(htable* ht) {
entry *del;
int i;
for(i = 0; i < ht->size; i++) {
while( (del = ht->entries[i]) ) {
ht->entries[i] = del->next;
free(del);
}
}
free(ht->entries);
free(ht);
}

freeing an array of lists

I got a memory leak in my program, and I can't understand why. I got a 4 size array of linked lists, and valgrind says there is a memory leak.
Here is my struct:
struct node {
achievementMen100m player;
char* playerName;
Men100mAchievement playerAchiInRound;
char*currentRound;
struct node *head;
struct node *next;
} node, *Node;
Here is my allocation in the create function:
for(int i=0; i<4;i++){
OG->games->head->phases[i] = malloc(sizeof(struct node)); //VALGRIND SAYS MEMORY ALLOCATED HERE NOT FREED!//
OG->games->head->phases[i]->head=NULL;
OG->games->head->phases[i]->next=NULL;
OG->games->head->phases[i]->playerAchiInRound = 0;
}
Here is my free-list function:
void listDestroy(struct node * list) {
struct node * currentPlayer = list;
struct node * temp;
while (currentPlayer != NULL) {
temp = currentPlayer;
currentPlayer=currentPlayer->next;
free(temp->playerName);
free(temp);
}
list = NULL;
free(list);
}
And this is the free function of the ADT:
void olympicGamesDestroy(OlympicGames OG) {
if (OG == NULL) {
return;
}
if (OG->games == NULL) {
free(OG);
return;
}
if (OG->games->head == NULL) {
free(OG->games);
free(OG);
return;
}
for (int i=0; i<4;i++) {
listDestroy(OG->games->head->phases[i]->head);
}
free(OG->games->next);
free(OG->games->head);
free(OG->games);
free(OG);
}
update
here is my entire .h file
typedef struct men100 {
Men100mAchievement olympicMinimum;
Men100mAchievement olympicSkipPre;
char* roundNames[4];
struct node* phases[4];
} men100, *Men100;
typedef struct gameList {
int name;
men100* head;
struct gameList *next;
} gameList, *GameList;
typedef struct olympicGames {
GameList games;
int numOfGames;
} olympicGames, *OlympicGames;
Your void olympicGamesDestroy(OlympicGames OG) looks strange!
You are allocating at OG->games->head->phases[i].
So, where are you freeing them? You are only working on OG->games->head->phases[i]->head and not on OG->games->head->phases[i].
Show the actual OlympicGames data structure.
UPDATE:
I don't have much time to verify the whole code:
But you can try the following:
for(int i=0; i<4; i++)
{
listDestroy(OG->games->head->phases[i]->head);
free(OG->games->head->phases[i]); // you need this
}

n-ary tree searching function

I'm trying to make a function for n-ary tree searching, but it doesn't work well, it returns wrong node after level 2. Anyone knows why?
Here is node implementation
typedef struct node
{
char name[30];
int year;
struct node* ptr;
struct node* p[10];
} node;
And there is a function
node *search(node *p, char* name, int year)
{
int i, n;
if(p == NULL)
return (NULL);
if((!strcmp(p->name, name) && (p->year == year))
return (p);
n = number(p); \\returns number of childs
for(i = 0; i < n; i++)
if(search(p->p[i], name, year))
return (p->p[i]);
}
You return the child that holds the requested node but not the node itself.
for(i = 0; i < n; i++)
{
if ((p2 = search(p->p[i], name, year)))
return p2;
}
return NULL;

Resources