2016-02-05 2 views
1

У моего кода проблема с утечкой памяти. Я не знаю, где я ошибся. Ниже приведен код: я пытаюсь прочитать из csv-файла и хранить определенные столбцы.Чтение из памяти csv и динамической памяти

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main() 
{ 
    FILE *result = fopen ("C:\\Users\\pa1rs\\Desktop\\local.csv", "w"); 

    const char *text = "LOA,NAME,"; 
    fprintf (result, "%s", text); 
    char *token; 
    char *endToken; 
    int lines = 0; 
    char ch;       /* should check the result */ 
    FILE *file = fopen ("C:\\Users\\pa1rs\\Desktop\\samplee.csv", "r"); 
    char line[300]; 
    if (file == NULL) { 
     perror ("Error opening the file"); 
    } else { 
     while (!feof (file)) { 
      ch = fgetc (file); 
      if (ch == '\n') { 
       lines = lines + 1; 
      } 
     } 
     //printf(" no of lines existing in the file %d\n\n", lines); 
    } 
    fseek (file, 0, SEEK_SET); 
    while ((ch = fgetc (file)) != '\n') { 
     // we don't need the first line on sample.csv 
     // as it is just the description part 
    } 
    int s[lines - 1]; 
    int j = 0; 
    char *N[lines - 1]; 
    while (fgets (line, sizeof (line), file)) { 
     int i = 0; 
     token = line; 
     do { 
      endToken = strchr (token, ','); 
      if (endToken) 
       *endToken = '\0'; 
      if (i == 3) { 
       s[j] = atoi (token); 
      } 
      if (i == 12) { 
       N[j] = (char *) malloc (strlen (token) * sizeof (char)); 
       strcpy (N[j], token); 
      } 

      if (endToken) 
       token = endToken + 1; 
      i++; 
     } while (endToken); 
     j = j + 1; 
    } 
//******************************************************unigue loa 
    int count = 0; 
    int g = 0; 
    int h = 0; 
    int LOA[lines - 1]; 
    int dd = 0; 
    for (dd = 0; dd < lines - 1; dd++) { 
     LOA[dd] = 0; 
    } 
    for (g = 0; g < lines - 1; g++) { 
     for (h = 0; h < count; h++) { 
      if (s[g] == LOA[h]) 
       break; 
     } 
     if (h == count) { 
      LOA[count] = s[g]; 
      count++; 
     } 
    } 
    int xw = 0; 
    for (xw = 0; xw < count; xw++) { 
     //printf("%d \t",LOA[xw]); 
    } 

    //printf("LOA Array Length is: %d \n",count); 


    //******************************************************** 
    ////FOR UNIQUE NAMES ARRAY 


    //printf("No of unique names are %d",county); 
    //FOR UNIQUE CAUSES ARRAY 
    char *sa[9] = 
     { "Monticello", "Valparaiso", "Crown Point", "Plymouth", "Goshen", 
"Gary", "Hammond", "Laporte", "Angola" }; 
    int countz = 0; 
    int gz = 0; 
    int hz = 0; 
    char *LOAz[lines - 1]; 
    int zero2 = 0; 
    for (zero2 = 0; zero2 < lines - 1; zero2++) { 
     LOAz[zero2] = NULL; 
    } 
    for (gz = 0; gz < lines - 1; gz++) { 
     for (hz = 0; hz < countz; hz++) { 
      if (strcmp (N[gz], LOAz[hz]) == 0) 
       break; 
     } 
     if (hz == countz) { 
      LOAz[countz] = (char *) malloc (strlen (N[gz]) * sizeof (char)); 
      strcpy (LOAz[countz], N[gz]); 
      countz++; 
     } 
    } 
    int nz = 0; 
    for (nz = 0; nz < countz; nz++) { 
     fprintf (result, "%s,", LOAz[nz]); 
    } 
    fprintf (result, "\n"); 
    // printf("%d",countz); 
    //***************************** 
    int i = 0; 
    int jjj = 0; 
    int xxx = 0; 
    int ggg = 0; 
    int k = 0; 
    int kount[count][countz]; 
    for (xxx = 0; xxx < count; xxx++) { 
     for (ggg = 0; ggg < countz; ggg++) { 
      kount[xxx][ggg] = 0; 
     } 
    } 
    for (i = 0; i < count; i++) { 
     for (k = 0; k < countz; k++) { 
      for (jjj = 0; jjj < lines - 1; jjj++) { 
       if (LOA[i] == s[jjj]) { 
        if (strcmp (LOAz[k], N[jjj]) == 0) { 
         kount[i][k]++; 

        } 
       } 

      } 
     } 
    } 

    int ig = 0; 
    int ik = 0; 
    for (ig = 0; ig < count; ig++) { 
     fprintf (result, "%d,%s", LOA[ig], sa[ig]); 
     for (ik = 0; ik < countz; ik++) { 
      fprintf (result, ",%d", kount[ig][ik]); 
     } 
     fprintf (result, "\n"); 
    } 
    int rrr = 0; 
    free (N); 
    for (rrr = 0; rrr < lines - 1; rrr++) { 
     free (LOAz[rrr]); 
    } 

    //***************************** 
    //fclose(result); 
    fclose (file); 
    return 0; 
} 

Линии я здесь 13761 и LOAz был объявлен с размером массива строк-1 = 13761, но уникальные, которые я получил здесь только 49, поэтому я перераспределении памяти, что и остальные не используются, я думаю, проблема началась. Пожалуйста, помогите! Заранее спасибо.

+0

Чтобы проследить утечки памяти, вы хотите использовать контролеры памяти, такие как Valgrind (https://valgrind.org). – alk

+0

Вы не можете закрыть 'result' после открытия с помощью' FILE * result = fopen'. Предполагая, что 'rrr' зацикливается на' countz' в 'LOAz [countz]', то неспособность закрыть файл является вашей единственной утечкой. Также, пожалуйста, организуйте свои объявления. Обычно вы должны объявлять свои переменные в начале каждого блока кода, а не в ad-hoc sprinklings в каждом блоке. –

ответ

1

Одна из проблем в вашем коде заключается в том, что вы не выделяете достаточно памяти для строк. Например, в этих строках:

N[j] = (char*) malloc(strlen(token) * sizeof(char)); 
strcpy(N[j], token); 
// ... 
LOAz[countz] = (char*) malloc(strlen(N[gz]) * sizeof(char)); 
strcpy(LOAz[countz], N[gz]); 

Проблема заключается в том, что strlen возвращает количество ненулевых символов в строке. Тем не менее, чтобы сохранить строку, вам нужен еще один байт, чтобы сохранить нулевой символ завершения, поэтому размер буфера для хранения s должен быть не менее strlen(s) + 1.

Кроме того, лучший стиль кодирования - to avoid casting the return value of malloc.

+2

sizeof (char) также довольно бесполезно –

+0

... отливки также. – alk

Смежные вопросы