logo
down
shadow

Is it a memory leak in C when code fails to free memory, but the OS will anyway?


Is it a memory leak in C when code fails to free memory, but the OS will anyway?

By : Jan Sobotka
Date : September 24 2020, 01:00 AM
it fixes the issue Yes and no.
Most programs are written with the expectation that they free their memory before termination. But most operating systems are written to not assume anything about the memory used by applications, so they will indeed reclaim that memory after a program has terminated.
code :


Share : facebook icon twitter icon
cocoa 64bit binaries leak memory? (releasing NSData does not free memory)

cocoa 64bit binaries leak memory? (releasing NSData does not free memory)


By : user1438016
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , First, use Instrument's Object Graph instrument to verify that the memory is no longer considered to be in use; does not have a retain count or a strong reference somewhere.
If it is no longer in use, then the memory is sticking around simply because you haven't hit the threshold at which the collector cares.
code :
NSData *bla = [[NSData alloc] initWithContentsOfFile:@"/bigpoop"];
Matplotlib errors result in a memory leak. How can I free up that memory?

Matplotlib errors result in a memory leak. How can I free up that memory?


By : user3438301
Date : March 29 2020, 07:55 AM
will be helpful for those in need I assume you can run the code you posted at least once. The problem only manifests itself after running the posted code many times. Correct?
If so, the following avoids the problem without really identifying the source of the problem. Maybe that is a bad thing, but this works in a pinch: Simply use multiprocessing to run the memory-intensive code in a separate process. You don't have to worry about fig.clf() or plt.close() or del a,b or gc.collect(). All memory is freed when the process ends.
code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np      

import multiprocessing as mp

def worker():
    N=1000000
    a = np.arange(N)
    b = np.random.randn(N)

    fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
    fig.set_size_inches(10,7)
    ax = fig.add_subplot(111)
    ax.plot(a, b)

    fig.savefig('/tmp/random.png')   # code gives me an error here

if __name__=='__main__':
    proc=mp.Process(target=worker)
    proc.daemon=True
    proc.start()
    proc.join()
Unable to free memory from struct arrays, valgrind shows memory leak

Unable to free memory from struct arrays, valgrind shows memory leak


By : Maudemick
Date : March 29 2020, 07:55 AM
it fixes the issue I have a nested struct to which I am dynamically assigning memory and creating arrays. So, its like a struct has rows and rows has columns both as structs. , The bug is quite subtle. In the allocation code, you have:
code :
(*result)->rows->n = colCount;
col_count= _r->rows[i].n;
(*result)->rows[i].n = colCount;
(*result)->rows[0].n = colCount;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "cJSON.h"

struct _str
{
    char *s; /**< string as char array */
    int len; /**< string length, not including null-termination */
};

typedef struct _str str;
typedef str *db_key_t;

typedef enum {
    DB_INT,        /**< represents an 32 bit integer number      */
    DB_BIGINT,     /**< represents an 64 bit integer number      */
    DB_DOUBLE,     /**< represents a floating point number       */
    DB_STRING,     /**< represents a zero terminated const char* */
    DB_STR,        /**< represents a string of 'str' type        */
    DB_DATETIME,   /**< represents date and time                 */
    DB_BLOB,       /**< represents a large binary object         */
    DB_BITMAP      /**< an one-dimensional array of 32 flags     */
} db_type_t;

typedef struct
{
    db_type_t type; /**< Type of the value                              */
    int nul;        /**< Means that the column in database has no value */
    int free;       /**< Means that the value should be freed */
    /** Column value structure that holds the actual data in a union.  */
    union
    {
        int int_val;              /**< integer value              */
        long long bigint_val;     /**< big integer value          */
        double double_val;        /**< double value               */
        time_t time_val;          /**< unix time_t value          */
        /*const*/ char *string_val;   /**< zero terminated string     */
        str str_val;              /**< str type string value      */
        str blob_val;             /**< binary object data         */
        unsigned int bitmap_val;  /**< Bitmap data type           */
    } val;
} db_val_t;
typedef struct db_row
{
    db_val_t *values;  /**< Columns in the row */
    int n;             /**< Number of columns in the row */
} db_row_t;

typedef struct db_res
{
    struct
    {
        db_key_t *names;   /**< Column names                    */
        db_type_t *types;  /**< Column types                    */
        int n;             /**< Number of columns               */
    } col;
    struct db_row *rows;   /**< Rows                            */
    int n;                 /**< Number of rows in current fetch */
    int res_rows;          /**< Number of total rows in query   */
    int last_row;          /**< Last row                        */
} db_res_t;

static
int parse_json_to_result(char *json, db_res_t **result)
{
    printf("received json: %s\n", json);
    cJSON *root, *record;
    int recordCount = 0;
    int colCount = 0;
    int i = 0;
    int j = 0;
    int int_val = 0;
    char *str_val = '\0';

    root = cJSON_Parse(json);
    recordCount = cJSON_GetArraySize(root);
    *result = calloc(1, sizeof(db_res_t));
    (*result)->n = recordCount;

    // malloc for number of rows.
    (*result)->rows = calloc(recordCount, sizeof(db_row_t) );

    // this is done to get the count of columns only once.
    record = cJSON_GetArrayItem(root, i);
    colCount = cJSON_GetArraySize(record);
    printf("Record count = %d\n", recordCount);
    printf("colCount-1 = %d\n", colCount);

    for (i = 0; i < recordCount; i++)
    {
        printf("Allocating record %d\n", i);
        j = 0;
        record = cJSON_GetArrayItem(root, i);
        (*result)->rows[i].n = colCount;
        printf("colCount-2 = %d\n", colCount);
        // malloc for number of columns in each row.
        (*result)->rows[i].values = calloc(colCount, sizeof(db_val_t) );
        cJSON *subitem = record->child;
        while (subitem)
        {
            if (subitem->type == cJSON_Number)
            {
                int_val =
                    cJSON_GetObjectItem(record, subitem->string)->valueint;
                (*result)->rows[i].values[j].type = DB_INT;
                (*result)->rows[i].values[j].nul = 0;
                (*result)->rows[i].values[j++].val.int_val = int_val;
//              printf("%d\n", int_val);
            }
            else
            {
                str_val =
                    cJSON_GetObjectItem(record, subitem->string)->valuestring;
//              printf("%s\n", str_val);
                (*result)->rows[i].values[j].type = DB_STRING;
                if (strcmp(str_val, "") == 0)
                {
                    (*result)->rows[i].values[j].nul = 1;
                    (*result)->rows[i].values[j].free = 0;
                    (*result)->rows[i].values[j++].val.string_val = NULL;
                }
                else
                {
                    static int count = 0;
                    printf("Allocate %d: %s\n", ++count, str_val);
                    (*result)->rows[i].values[j].nul = 0;
                    (*result)->rows[i].values[j].free = 1;
                    (*result)->rows[i].values[j++].val.string_val = strdup(str_val);
                }
            }
            subitem = subitem->next;
        }
    }
    cJSON_Delete(root);
    return 1;
}

static
int free_result(db_res_t *_r)
{
    if (!_r)
    {
        return -1;
    }
    int i, row_count = 0;
    int col_count = 0;
    printf("freeing result set at %p\n", _r);
    row_count = _r->n;
    printf("RowCount %d .\n", row_count);
    for (i = 0; i < row_count; i++)
    {
        printf("Freeing %d row.\n", i);
        col_count = _r->rows[i].n;
        printf("col_count %d.\n", col_count);
        int j = 0;
        for (j = 0; j < col_count; j++)
        {
            if (_r->rows[i].values[j].type == DB_STRING && _r->rows[i].values[j].nul == 0)
            {
                printf("Freeing-1 %d col [%s]\n", j, _r->rows[i].values[j].val.string_val);
                free(_r->rows[i].values[j].val.string_val);
                _r->rows[i].values[j].val.string_val = NULL;
            }
            else if (_r->rows[i].values[j].type == DB_STR  && _r->rows[i].values[j].nul == 0)
            {
                printf("Freeing-2 %d col [%s]\n", j, _r->rows[i].values[j].val.string_val);
                free(_r->rows[i].values[j].val.str_val.s);
                _r->rows[i].values[j].val.str_val.s = NULL;
            }
        }
        // free all value colums for each row.
        free(_r->rows[i].values);
        _r->rows[i].values = NULL;
    }
    // free all rows
    free(_r->rows);
    _r->rows = NULL;
    // free resultset
    free(_r);
    _r = NULL;
    // this will print nil.
    printf("freed result set a %p\n", _r);
    return 0;
}

int main(void)
{
    db_res_t *result = NULL;
    char json[] =
            "[{\"id\":11,\"username\":\"microsip\",\"domain\":\"192.168.254.128\","
            "\"event\":\"presence\",\"etag\":\"a.1437194656.2922.1.0\",\"expires\":1437200355,"
            "\"received_time\":-1,\"body\":\"\",\"extra_hdrs\":\"\",\"sender\":\"\"},"
            "{\"id\":12,\"username\":\"microsip\",\"domain\":\"92.168.254.128\",\"event\":\"presence\","
            "\"etag\":\"a.1437194656.2922.1.0\",\"expires\":1437200355,\"received_time\":-1,"
            "\"body\":\"\",\"extra_hdrs\":\"\",\"sender\":\"\"}]";

    parse_json_to_result(json, &result);
    free_result(result);
    return 0;
}
received json: [{"id":11,"username":"microsip","domain":"192.168.254.128","event":"presence","etag":"a.1437194656.2922.1.0","expires":1437200355,"received_time":-1,"body":"","extra_hdrs":"","sender":""},{"id":12,"username":"microsip","domain":"92.168.254.128","event":"presence","etag":"a.1437194656.2922.1.0","expires":1437200355,"received_time":-1,"body":"","extra_hdrs":"","sender":""}]
Record count = 2
colCount-1 = 10
Allocating record 0
colCount-2 = 10
Allocate 1: microsip
Allocate 2: 192.168.254.128
Allocate 3: presence
Allocate 4: a.1437194656.2922.1.0
Allocating record 1
colCount-2 = 10
Allocate 5: microsip
Allocate 6: 92.168.254.128
Allocate 7: presence
Allocate 8: a.1437194656.2922.1.0
freeing result set at 0x10082b0a0
RowCount 2 .
Freeing 0 row.
col_count 10.
Freeing-1 1 col [microsip]
Freeing-1 2 col [192.168.254.128]
Freeing-1 3 col [presence]
Freeing-1 4 col [a.1437194656.2922.1.0]
Freeing 1 row.
col_count 0.
freed result set a 0x0
received json: [{"id":11,"username":"microsip","domain":"192.168.254.128","event":"presence","etag":"a.1437194656.2922.1.0","expires":1437200355,"received_time":-1,"body":"","extra_hdrs":"","sender":""},{"id":12,"username":"microsip","domain":"92.168.254.128","event":"presence","etag":"a.1437194656.2922.1.0","expires":1437200355,"received_time":-1,"body":"","extra_hdrs":"","sender":""}]
Record count = 2
colCount-1 = 10
Allocating record 0
colCount-2 = 10
Allocate 1: microsip
Allocate 2: 192.168.254.128
Allocate 3: presence
Allocate 4: a.1437194656.2922.1.0
Allocating record 1
colCount-2 = 10
Allocate 5: microsip
Allocate 6: 92.168.254.128
Allocate 7: presence
Allocate 8: a.1437194656.2922.1.0
freeing result set at 0x10082b0a0
RowCount 2 .
Freeing 0 row.
col_count 10.
Freeing-1 1 col [microsip]
Freeing-1 2 col [192.168.254.128]
Freeing-1 3 col [presence]
Freeing-1 4 col [a.1437194656.2922.1.0]
Freeing 1 row.
col_count 10.
Freeing-1 1 col [microsip]
Freeing-1 2 col [92.168.254.128]
Freeing-1 3 col [presence]
Freeing-1 4 col [a.1437194656.2922.1.0]
freed result set a 0x0
Is there any code snippet demonstrate the harm of memory leak or fogeting free memory malloced

Is there any code snippet demonstrate the harm of memory leak or fogeting free memory malloced


By : abcefg
Date : March 29 2020, 07:55 AM
I hope this helps you . Okay I will explain the problem.
Computers has limited memory ( modern personal one has about 8 Gigabytes). Operating systems and apps need the memory so their code can be loaded into it and executed by the CPU. Modern systems split the memory into equally sized chunks called pages, the actual page size differs from system to another
What is the difference between memory leak, accessing freed memory and double free?

What is the difference between memory leak, accessing freed memory and double free?


By : Nastynas69
Date : March 29 2020, 07:55 AM
Does that help Memory leaks are bad. Double frees are worse. Accessing freed memory is worser. Memory leaks
This is not an error per se. A leaking program is stil valid. It may not be a problem. But this is still bad; with time, your program will reserve memory from the host and never release it. If the host's memory is full before the program completion, you run into troubles.
code :
// dont do this at home
int* n = new int{};
delete n;
std::cout << *n << "\n"; // UNDEFINED BEHAVIOUR. DONT.
Related Posts Related Posts :
  • C: What does if(a<b<c) do?
  • What does this mean exactly in C?
  • What is the best way to achieve sscanf-like functionality in Perl?
  • How to create threads and sort correctly in a odd-even sorting program?
  • What's the single best reference on the topic of (POSIX) signals?
  • Avoid Overflow when Calculating π by Evaluating a Series Using 16-bit Arithmetic?
  • How to handle data or char -1 when reading from file, since EOF is also -1
  • Compare every 1kb of contents of two files instead of character by character
  • Understanding functions in stm8s disassembly?
  • Recursive and no-recursive get different answer
  • Can anyone explain the following output of the code?
  • How to resync time from NTP server in esp-idf?
  • Output for the following C code is confusing me
  • Determine if window is visible with High CPU
  • Writing a file by taking input from user only saves value for "x" only
  • How should I fill an array of ints from a file using command line args? The size of the file and the no. of elements may
  • Segmentation Fault While Reading File in C
  • Fill an array at index n with m times data without bit-fields
  • Why don't the values I type in the terminal match the values I've already stored in the array?
  • MPLABX XC16 unable to resolve built-in identifier __builtin_dmaoffset
  • How call and compile function from elf to my binary?
  • Modifying non-const char array that is referred to by const char array
  • Does anyone see any mistakes here? I am trying to get a message via a pipe, from my parent to child
  • Memory Leak - Singly linked list in C
  • Trouble with translation of typedef between C to D
  • Why does SIGINT stop sleep more than one time?
  • How to pause a timer created with CreateTimerQueueTimer
  • How can I read data from file ? I can't fix it
  • Scanf in visual studio not accepting multiple cases of characters
  • How can I determine if a char* is a windows line ending?
  • I am trying to store value in long long int type but giving wrong return
  • How to manage different kinds of data in a linked list?
  • uint8_t not rollover to 0 after reaching 255 not working properly
  • Why do these two execvp produce different results?
  • Pass uintmax_t or size_t to custom printf conversion specifier
  • Why does free() leaves stuff in memory?
  • Why pointers can't be used to index arrays?
  • memory allocation eror in C
  • C custom datatypes mapped to C datatypes grouped under a single struct
  • pipe() data is not transferred to child process
  • Getting a core dump from a simple C program
  • Fatal error on makefile, need to understand the problem
  • How can I add a delay of 90 minutes when a port has gone from 0 to 1?
  • To use strcpy or not
  • the usage of strtok() in c shows warnings and returns segmentation fault(core dumped)
  • Trouble allocating array of structs
  • Only first char of user input used in array
  • Why does "int x = 5; printf("%d %d %d", x==5, x=10, x==5);" in C print "0 10 0"?
  • How to scan specific string format in C?
  • sscanf skipping the final value when reading multiple values from a line
  • How can I access full memory space in FreeDOS with C application
  • Semantics of sem_getvalue() in POSIX
  • What does the [x,y] symbol mean in a multidimensional array access?
  • compilation error: cast from pointer to integer of different size
  • why am i getting compilation error "error: conflicting types for ‘ptr’ " for the following code? static int va
  • Why does getw return -1 when trying to read a character?
  • Why C program in whch two functions call each other recursively gives segmentation fault on linux?
  • ssize_t is undefined
  • Passing a generic argument in a C function
  • Restoring stdout after redirecting it via freopen()
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk