I got this off a website. First, I adapted it to my code. Then just did a paste for test. It gives this error right after it prints the directory listing. Can anyone tell me what is the problem?
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command
" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
*** Error in `popenbin': free(): invalid next size (normal): 0x0000000001deacb0 ***
Aborted (core dumped)
I understand that “works for me” is not really helpful, but without any information about distribution, its version, compiler version, exact compiler options etc there is not much more to say. I do not see anything in code itself that may cause memory corruption.
// while (fgets(linebuffer, sizeof(linebuffer), FilePtr) != NULL)
// printf(“%s”, linebuffer);
Find the above statement. Comment out, no errors.
This code is the original which shows no errors.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command
" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
Give gdb a try, the GNU debugger. It admittedly has a steep learning curve, but it really lets you inspect things in detail between single-stepping through your source. The kind of insight gained with a debugger is unrivaled (yet often avoided even by professional coders) in my opinion.
I personally use gdb with a slightly modified GDB dashboard.
Kdbg and Kdevelop I’v downloaded as well. There is valgrind to detect memory leaks.
I ran valgrind.
#valgrind --leak-check=yes scanvirusbin -v
==8839== Invalid write of size 1
==8839== at 0x4C319B0: strcpy (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==8839== by 0x4015D6: main (in /root/bin/scanvirusbin)
==8839== Address 0x51f89d8 is 0 bytes after a block of size 8 alloc'd
==8839== at 0x4C2E2DF: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==8839== by 0x4015BB: main (in /root/bin/scanvirusbin)
Valgrind showed an error in the memory allocation. The sizeof function wasn’t giving a useful number. Since, I borrowed this code. I missed what was causing the problem.
It’s not sizeof. It’s the variable len. I should be able to fix the memory allocation bug.