malloc'd memory goes to NULL when control goes out of funtion's scope

I heard that malloc() allocates memory from the heap which doesn't go away until you free() the memory, but when I run this program, I get "Hello" for the initialize() funtion and "(null)" for the main function. Can anyone tell me why this is so?

I am running this program in fedora linux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
    char value[40];
    struct node* next;
    struct node* prev;
} node;

typedef struct head {
    node* first;
} head;
head HashTable[1];
void initialize();

int main() {
    initialize();
    node* theNode = HashTable[1].first;
    printf("Value in main: %s\n", theNode->value);
    free(theNode);
}

void initialize() {
    node* myNode = malloc(sizeof(node));
    HashTable[0].first = myNode;
    char* myBuffer = malloc(40);
    strcpy(myBuffer, "Hello");
    strcpy(myNode->value, myBuffer);
    printf("Value in initialize: %s\n", myNode->value);
}
Line 19: HashTable[1] doesn't exist. You mean HashTable[0], right?

Also, you are allocating a chunk of memory on line 27 but never freeing it. There is no need to use it, though. Just strcpy() the string directly to the target array/buffer.

24
25
26
27
28
29
void initialize() {
    node* myNode = malloc(sizeof(node));
    HashTable[0].first = myNode;
    strcpy(myNode->value, "Hello");
    printf("Value in initialize: %s\n", myNode->value);
}

Hope this helps.
Topic archived. No new replies allowed.