c - Why do I get a still reachable block after mallocing a char*? -


i have following code:

#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h>  void print_usage() {   printf("%s\n", "usage"); }  int file_exist (char *filename) {   struct stat   buffer;      return (stat (filename, &buffer) == 0); }  int parse_parameters(int argc, char *argv[], char** in) {   unsigned int i1 = 1; // 0 filename   (; i1 < argc; ++i1)   {     if( 0 == strcmp("-h", argv[i1]) )     {       print_usage();       return 0;     }     else if( 0 == strcmp("-i", argv[i1]) )     {       *in = malloc( sizeof(char) * strlen(argv[++i1]) + 1 );       strcpy(*in, argv[i1]);       continue;     }     else     {       print_usage();       return 1;     }   }   return 0; }  int main(int argc, char *argv[]) {   if( argc != 3 )   {     print_usage();     return 0;   }    char* in = null;    int parse = parse_parameters(argc, argv, &in);   if ( 0 != parse )     return parse;    printf("in: %s\n", in);    file* finput = null ;   if (file_exist(in))     finput = fopen(in, "r");   if (finput == null) {       perror("fopen");       exit(1);   }    free(in);   fclose(finput);   return 0; } 

after running valgrind following parameters:

./main -i input 

i following:

==30977== memcheck, memory error detector ==30977== copyright (c) 2002-2013, , gnu gpl'd, julian seward et al. ==30977== using valgrind-3.10.0.svn , libvex; rerun -h copyright info ==30977== command: ./main -i input ==30977==  in: input fopen: no such file or directory ==30977==  ==30977== heap summary: ==30977==     in use @ exit: 6 bytes in 1 blocks ==30977==   total heap usage: 2 allocs, 1 frees, 574 bytes allocated ==30977==  ==30977== 6 bytes in 1 blocks still reachable in loss record 1 of 1 ==30977==    @ 0x4c2ab80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==30977==    0x400946: parse_parameters (main.c:31) ==30977==    0x4009e7: main (main.c:54) ==30977==  ==30977== leak summary: ==30977==    lost: 0 bytes in 0 blocks ==30977==    indirectly lost: 0 bytes in 0 blocks ==30977==      possibly lost: 0 bytes in 0 blocks ==30977==    still reachable: 6 bytes in 1 blocks ==30977==         suppressed: 0 bytes in 0 blocks ==30977==  ==30977== counts of detected , suppressed errors, rerun with: -v ==30977== error summary: 0 errors 0 contexts (suppressed: 0 0) 

why ? if try pass in char* won't changed after parse_parameters function.

your program exiting result of exit (1) call, occurs before free (in). result seeing valgrind message.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -