So, I am writing a simple shell program and in my function main, I called “strcmp” to check if the command entered is “env” and “exit”. My code compiles fine but when I run valgrind to check error and memory leak, it brought up segmentation fault as well as “invalid read of size 1 at address”
I expected that when I run “valgrind”, I would get all memory freed
This is the error message:
Invalid read of size 1
==1877== at 0x483FED4: strcmp (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==1877== by 0x109806: main (in /root/simple_shell/hsh)
==1877== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==1877==
==1877==
==1877== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==1877== Access not within mapped region at address 0x0
==1877== at 0x483FED4: strcmp (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==1877== by 0x109806: main (in /root/simple_shell/hsh)
This is my function main:
if (tokens == NULL)
{
/* free env before exiting shell */
free_env(env_cp);
return (-1);
}
/* check if the entered command is exit */
if (strcmp(tokens[0], "exit") == 0)
{
free_env(env_cp);
/* Free the allocated memory for tokens */
for (i = 0; tokens[i] != NULL; i++)
{
free(tokens[i]);
}
free(tokens);
exit(EXIT_SUCCESS);
}
/* check if the entered command is env */
if (strcmp(tokens[0], "env") == 0)
{
print_env(env_cp);
/* Free the allocated memory for tokens */
for (i = 0; tokens[i] != NULL; i++)
{
free(tokens[i]);
}
free(tokens);
continue;
}
execmd(tokens);
/* Free the allocated memory for tokens */
for (i = 0; tokens[i] != NULL; i++)
{
free(tokens[i]);
}
free(tokens);
}
free_env(env_cp);
return (0);
}