Quantcast
Channel: Maris Labs
Viewing all articles
Browse latest Browse all 19

Fixed file() memory leak and access violations

$
0
0

New function definition:

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
32
33
34
35
36
int file(const char * filename, char *elements[], unsigned char flags) {
    int line_count = 0;
   
    FILE *fp;
    if ((fp = fopen(filename, "r")) == NULL) return -1;

    char *s;
    size_t s_len;
   
    while (!feof(fp)) {

        if ((s = (char *) calloc(LINE_MAX, sizeof(char))) == NULL) {
            fclose(fp);
            return -1;
        }
       
        fgets(s, LINE_MAX, fp);
        s_len = strlen(s);

        if (!(flags & FILE_NO_FLAGS)) {
            if ((flags & FILE_SKIP_EMPTY_LINES) && s_len == 0) {
                free(s); s = NULL; continue;
            }
           
            if ((flags & FILE_IGNORE_NEW_LINES) && s_len > 0)
                if (s[s_len - 1] == '\n') s[s_len - 1] = '\0';
        }
       
        elements[line_count] = s;
        line_count++;
    }
   
    fclose(fp);
   
    return line_count;
}

Valgrind memory diagnostic report:

==62234== Memcheck, a memory error detector
==62234== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==62234== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==62234== Command: ./program
==62234==
--62234-- ./program:
--62234-- dSYM directory is missing; consider using --dsymutil=yes
The most useful information for each sync...
sync path = *******
sync path = *******
sync path = *******
==62234==
==62234== HEAP SUMMARY:
==62234==     in use at exit: 6,069 bytes in 33 blocks
==62234==   total heap usage: 41 allocs, 8 frees, 24,501 bytes allocated
==62234==
==62234== LEAK SUMMARY:
==62234==    definitely lost: 0 bytes in 0 blocks
==62234==    indirectly lost: 0 bytes in 0 blocks
==62234==      possibly lost: 0 bytes in 0 blocks
==62234==    still reachable: 6,069 bytes in 33 blocks
==62234==         suppressed: 0 bytes in 0 blocks
==62234== Rerun with --leak-check=full to see details of leaked memory
==62234==
==62234== For counts of detected and suppressed errors, rerun with: -v
==62234== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Viewing all articles
Browse latest Browse all 19

Trending Articles