-3

I have got into a problem of memory leak in my code. I believe it is from stdin . I tried to close(0), did not work. Below is my code

 char line[MAX_BUFFER] = {};
    char *commands;
    while(!feof(stdin)) {
         fputs("? ",stdout);

        if(fgets(line, MAX_BUFFER , stdin))
        {
            Command cmd = {};
            commands =  parse(&cmd, line);
            printf("%s",commands);
           free(commands);

         }

    }

    return 0;

my parse.c basically do this

    char result[250] = "some text string here";
    char *target  = malloc(sizeof(char) * 250);
    target = strdup(result);
    return target

and my valgrind output looks like this

==26303== FILE DESCRIPTORS: 3 open at exit.
==26303== Open file descriptor 2: /dev/pts/4
==26303==    <inherited from parent>
==26303== 
==26303== Open file descriptor 1: /dev/pts/4
==26303==    <inherited from parent>
==26303== 
==26303== Open file descriptor 0: /dev/pts/4
==26303==    <inherited from parent>
==26303== 
==26303== 
==26303== HEAP SUMMARY:  
==26303==     in use at exit: 500 bytes in 2 blocks
==26303==   total heap usage: 4 allocs, 2 frees, 545 bytes allocated
==26303== 
==26303== 500 bytes in 2 blocks are definitely lost in loss record 1 of 1

1 Answers1

0

Both strdup() and malloc() are allocating memory! You can get rid of the second line in your parse.c and edit the third to say

char * target = strdup(result);

and it would work fine.

Also don't forget to free the memory once you're done with it using free(pointerToMemoryAllocated)

David Harvey
  • 624
  • 4
  • 12