Проблема с утечкой памяти C

#c #memory-leaks

#c #утечки памяти

Вопрос:

 your program did not free all of the memory it allocated
==17711== Memcheck, a memory error detector
==17711== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==17711== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==17711== Command: ./counter
==17711==
==17711== Conditional jump or move depends on uninitialised value(s)
==17711==    at 0x400B98: main (counter.c:105)
==17711==
==17711== Conditional jump or move depends on uninitialised value(s)
==17711==    at 0x400BDB: main (counter.c:107)
==17711==
==17711== Conditional jump or move depends on uninitialised value(s)
==17711==    at 0x400C1B: main (counter.c:109)
==17711==
error
==17711==
==17711== HEAP SUMMARY:
==17711==     in use at exit: 64 bytes in 4 blocks
==17711==   total heap usage: 4 allocs, 0 frees, 64 bytes allocated
==17711==
==17711== LEAK SUMMARY:
==17711==    definitely lost: 0 bytes in 0 blocks
==17711==    indirectly lost: 0 bytes in 0 blocks
==17711==      possibly lost: 0 bytes in 0 blocks
==17711==    still reachable: 64 bytes in 4 blocks
==17711==         suppressed: 0 bytes in 0 blocks
==17711== Rerun with --leak-check=full to see details of leaked memory
==17711==
==17711== For counts of detected and suppressed errors, rerun with: -v
==17711== Use --track-origins=yes to see where uninitialised values come from
==17711== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 6 from 6)
make: *** [test_counter] Error 1
  

У меня утечка памяти в этой программе … я почти уверен, что я уже освободил всю свою динамическую память.. Я не понимаю, где утечка =

 #include "counter.h"

/* ============================================================================
 * File-global variables
 * ========================================================================== */
static int ncounters = 0;
static struct counter *counters = NULL;

static int nthreads = 0;
static int *ninstructions = NULL;
static struct instruction **instructions = NULL;


/* ============================================================================
 * Operations
 * ========================================================================== */
static void
decrement(long long *n) {
        (*n)--;
}

static void
increment(long long *n) {
    (*n)  ;
}

static void
mult2(long long *n) {
    (*n)=(*n)*2;
}


/* ============================================================================
 * Helper functions
 * ========================================================================== */

pthread_mutex_t lock1;

/* ============================================================================
 * Thread function
 * ========================================================================== */
static void *
worker_thread(void *arg) {

        pthread_mutex_lock( amp;lock1 );

        long long n = (long long)arg;
        for(int i=0; i < ninstructions[n] ;i  ){
          for(int j=0; j < instructions[n][i].repetitions ;j  ){
            (*instructions[n][i].work_fn)(amp;((instructions[n][i].counter)->counter));
          }
        }
        pthread_mutex_unlock( amp;lock1 );
    return NULL;
}


/* ============================================================================
 * Main function
 * ========================================================================== */
int
main(void) {

        scanf(" %d", amp;ncounters); //Ask for number of counters

        int i;

        if((counters = malloc(sizeof(struct counter)*ncounters))){
          for( i=0; i < ncounters ;i  ){
            counters[i].counter = 0;
          }
        }

        scanf(" %d", amp;nthreads); //Ask for number of threads

        if((ninstructions = (int*) malloc(nthreads*sizeof(int)))){
          for( i=0; i < nthreads ;i  ){
            ninstructions[i] = 0;
          }
        }

        instructions = malloc(nthreads*sizeof(struct instruction *));

        for(i=0; i < nthreads ;i  ){

          scanf(" %d", amp;ninstructions[i]);  //Ask for number of instructions within threads[i]

          instructions[i] = malloc(ninstructions[i]*sizeof(struct instruction));
          for(int j=0;j < ninstructions[i] ;j  ){
            int Srepetition;
            char Sfunction;
            int Scounter;

            scanf(" %d %c %d", amp;Scounter, amp;Sfunction, amp;Srepetition);

            instructions[i][j].repetitions = Srepetition;

            instructions[i][j].counter = (counters Scounter);

            if(Sfunction == 'I'){
              instructions[i][j].work_fn = increment;
            }else if(Sfunction == 'D'){
              instructions[i][j].work_fn = decrement;
            }else if(Sfunction == '2'){
              instructions[i][j].work_fn = mult2;
            }else{
              printf("errorn");
            }

          }

        }

        pthread_t thread_id[nthreads];

        for(long long i=0; i < nthreads ;i  ){
          pthread_create( amp;thread_id[i], NULL, worker_thread, (void *)i);
        }

        for(int i=0; i < nthreads ;i  ){
          pthread_join( thread_id[i], NULL);
        }

        for(i=0; i < ncounters ;i  ){
          printf("%lldn", counters[i].counter);
        }

        for(int i=0; i< nthreads;i  ){
          free(instructions[i]);
        }
        free(instructions);
        free(ninstructions);
        free(counters);
    return 0;
}
  

Комментарии:

1. Пожалуйста, добавьте весь соответствующий код сюда . Неразумно ожидать, что люди будут переходить по ссылкам, чтобы понять, о чем вы говорите…

2. Итак, я не получаю то, что я все еще не освободил

3. Я предлагаю вам попробовать удалить некоторые элементы из вашего кода, пока отчет Valgrind не станет чистым. Последнее, что вы удалили, будет причиной проблемы.

Ответ №1:

Вы освобождаете память, которая instructions занимает:

 free(instructions); 
  

Затем вы получаете доступ к этой памяти:

 for(int i=0 ; i < nthreads ; i  ){
    free(instructions[i]); 
} 
  

Вы не можете получить доступ instructions после вас free(instructions) .

Сначала вам нужно освободить указатели в instructions , затем освободить instructions массив.

Комментарии:

1. Обратите внимание на будущее, всегда устанавливайте значение освобожденного указателя равным NULL. Таким образом, вы получите очень простой в отладке сбой, если попытаетесь что-то дважды освободить или разыменовать указатель после его освобождения.

2. На самом деле у меня есть бесплатные инструкции для цикла [i], а затем бесплатные инструкции в моем коде.

3. @Jono: Нет, это не так. free(instructions) Сначала вы просматриваете содержимое instructions .

4. @Jono: Есть ли в структуре counter какие-либо необработанные указатели, получающие память? @James — Я думаю, что OP говорит об исходном коде, а не о том, который опубликован здесь в его комментарии.

5. извините, последняя версия. опубликовано

Ответ №2:

Пожалуйста, добавьте опцию --leak-check=full и, возможно --show-reachable=yes , в Valgrind и опубликуйте результат вместе с текущим исходным кодом. Конечно, запустите Valgrind для отладочной версии вашего исполняемого файла.

Комментарии:

1. на самом деле это был предоставленный автоматический тестовый пример, я пока не знаю, как запустить valgrind =