-1

So I am currently using a method where I have to malloc space for making an object. Anyone knows how can I free the space in the method when I want to end the program. Right now I keep on getting memory errors when I try to make space.

struct linkedlist *newNode(int val) { 
    struct linkedlist *node = (struct linkedlist *)malloc(sizeof(struct linkedlist)); 
    node->data = val; 
    node->next = NULL; 

    return node; 
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
www.com
  • 1
  • 4
  • 4
    You allocate memory with `malloc()`, you free memory with `free()` by passing it the value `malloc()` returned as its argument. Also, [it's a good idea to not cast the return value of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Nikos C. Sep 19 '20 at 13:48
  • 1
    Interesting that you tag "free", are asking for "free", but didn't find `free()`.... Google is your friend. – JHBonarius Sep 19 '20 at 13:57
  • I know what is free but I am a bit confused on how I can use it on this method – www.com Sep 19 '20 at 13:59
  • What are you trying to do? Why do you want to free memory in this method? IMHO it's not required here. You should write a separate method to clean up the objects... – JHBonarius Sep 19 '20 at 14:05
  • I retracted the close vote and cannot vote close again, but this is a duplicate of https://stackoverflow.com/q/37473620 – JHBonarius Sep 19 '20 at 14:09
  • The `newNode()` function looks like it's supposed to create new nodes, not free them. You must free the node once the program has no further use for it. If you free it in `newNode()`, then what's the point of that function? – Nikos C. Sep 19 '20 at 15:47
  • Does this answer your question? [How do malloc() and free() work?](https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work) – Rob Sep 19 '20 at 16:36

2 Answers2

1

The obvious answer is too obvious; so I'm going to assume you need a "less obvious" answer. There are 2 things I can think of.

Freeing a whole linked list (not just one node)

You want to make sure you don't use memory after it's freed. For linked lists this means that you should not do this:

    while(node != NULL) {
        free(node);
        node = node->next;   // BUG
    }

To avoid this problem you should use a temporary variable, like this:

    while(node != NULL) {
        temp = node->next;
        free(node);
        node = temp;
    }

Freeing before exit

For most operating systems there are layers of memory management (heap, management of virtual pages and virtual address spaces, management of physical RAM). When you free memory from the heap (free()) it doesn't necessarily de-allocate the underlying virtual memory or de-allocate the underlying physical memory - the underlying memory is often kept as allocated at lower levels to improve the performance of a future allocations from the heap.

When your program exits (or crashes), the OS has to clean up the resources it was using, including destroying/de-allocating the entire virtual address space your program was using and everything that it contained (including anything on the heap that you didn't free with free()). Because this is done using a "wholesale" approach (not a "piecemeal" approach), and because it's done at a lower level (bypassing the overhead of heap management), and because it's done by the kernel itself (bypassing the cost of system calls and transitions across the barrier between user-space and kernel-space), and because it must happen anyway (regardless of whether you free() or not); it can be significantly faster and just as effective to not bother freeing anything on the heap before your program exits.

The main reason to free() memory before exit is to detect memory leaks - anything still allocated (after you try to free everything) is memory that your program lost track of. However, most people don't build these kinds of checks into their software, and if they do it's easy enough to make it optional (e.g. use an "#ifdef MEM_LEAK_TEST_AT_EXIT" so it can be enabled during testing but disabled for release).

Brendan
  • 35,656
  • 2
  • 39
  • 66
  • Thanks for the information but that did not solve my problem – www.com Sep 19 '20 at 15:05
  • @www.com: Can you describe the problem more clearly? The only other thing I can think of is that maybe you're trying to make it so that a person can call the function to create a new node without worrying about freeing that new node later (where internally the code to create a node uses `atexit()` to ensure the node is freed if the program exits so that a caller doesn't have to worry); but this would be awful (error prone and slow), and I feel like I'm stretching my imagination way too far in my attempt to guess what the question is. – Brendan Sep 19 '20 at 15:34
0

Most Probably, (Assuming you are doing competitive programming), there is some other flaw in the code. But, as far as your doubt is concerned, you can do that in following manner:

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

free(node);

Get full details here: https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

Aman Desai
  • 233
  • 2
  • 11