I have found similar questions to mine here is StackOverFlow but I couldn't find a solution to my exact case.
I am trying to take user input as commands to execute them using getline function in C, so I allocated memory for a buffer to hold the input char *buffer
, and I allocated an array of pointers to be passed to execve to execute the command char **p_buffer
with p_buffer[0] = buffer
, and then I call fork : so I can call execve in the child process only,
at the bottom of my code a called free two time : one for buffer
and one for p_buffer
but when I use valgrind to check for memory leaks I get:
==102098== HEAP SUMMARY:
==102098== in use at exit: 100 bytes in 1 blocks
==102098== total heap usage: 5 allocs, 4 frees, 5,356 bytes allocated
==102098==
==102098== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==102098== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-
gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==102098== by 0x1092F0: create_buffers (functions.c:15)
==102098== by 0x109431: main (shell.c:23)
==102098==
==102098== LEAK SUMMARY:
==102098== definitely lost: 100 bytes in 1 blocks
==102098== indirectly lost: 0 bytes in 0 blocks
==102098== possibly lost: 0 bytes in 0 blocks
==102098== still reachable: 0 bytes in 0 blocks
==102098== suppressed: 0 bytes in 0 blocks
==102098==
==102098== For lists of detected and suppressed errors, rerun with: -s
==102098== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
this is My code:
25 while (mode)
26 {
27 mode = isatty(STDIN_FILENO);
28 if (mode)
29 write(STDOUT_FILENO, "#cisfun$ ", 9);
30 if (getline(&buffer, &i, stdin) == -1)
31 perror("Failed to read from stdin"), exit(2);
32 for (j = 0; buffer[j] != '\n'; j++){}; /* these two lines are just to remove the */
33 buffer[j] = '\0', p_buffer[0] = buffer; /* newline char at the end of buffer */
34 my_pid = fork();
35 if (!my_pid)
36 {
37 if (execve(p_buffer[0], p_buffer, env) == -1)
38 perror(av[0]);
39 }
40 else
41 wait(NULL);
42 }
43 free(p_buffer);
44 free(buffer);