1

I've defined a struct with typedef that is called Node. One of it's member is the key which is a pointer of the char type so that I can assign a value to it dynamically.

The header file for Node is cnode.h

#include <stdio.h>

typedef struct Node {
    char *key;
    int value;
    Node *next = NULL;
    
} Node;

void print_node(Node x){
    printf("[%s, %d]\n",x.key, x.value);
    
}

void print_list(Node head){
    printf("\n");
    while (head.next !=NULL){
        print_node(head);
        head = *head.next;
        printf("-->");
    }
    print_node(head);
}

Now I'm declaring the Node as set[SIZE]. I'm trying to create a set like structure for accessing value nearly O(1) time.

The location of my insertion is computed by a hash function. I'm inserting the value by an external function void insert().

For sanity check I'm printing the value of key both in the insert() function and main() function. But the result is not same in the both functions.

Here is the main program.

#include <stdio.h>
#include "cnode.h"

#define CAPACITY 50

unsigned long hash_function(int x)
{
    unsigned long i;
    i = x*(x+3)+x; //Knuth Variant on Division
    return i % CAPACITY;
}



void insert(Node *set, int value){
    char key[20];
 
    sprintf(key, "%d", value);

    int loc = hash_function(value);
    
    set[loc].key = key;
    set[loc].value = value;
 
    print_node(set[loc]);

}

int main(){
    Node set[CAPACITY];

    insert(set, 18);
    insert(set, 122);
    
    printf("\nVALIDATION\n");
    print_node(set[46]);
    print_node(set[22]);

}

I'm compiling my code with g++.

g++ -o main main.c && ./main 

The output:

[18, 18]
[122, 122]

VALIDATION
[�7�H�, 18]
[�7�H�, 122]

I've tried many thing with pointer and address. But still I couldn't fix the garbage output. What am I missing here?

exiled
  • 305
  • 2
  • 11
  • 2
    Does this answer your question? [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) `set[loc].key = key;` saves a pointer to a local variable, and then you try to use it after the local variable has been destroyed. – Raymond Chen Oct 13 '22 at 15:32

1 Answers1

1

In this line

set[loc].key = key;

key is a temporary value that will be deleted after the function completes.

What you want to do is use malloc to allocate permanent memory

char *newkey = (char *)malloc(16*sizeof(char)); // allocate room for 16 characters
sprintf(newkey, "%d", value);¨
set[loc].key = newkey;
Sven Nilsson
  • 1,861
  • 10
  • 11