Please review the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *some_text = "THIS IS SOME ARBITRARY TEXT FOR TESTING THE STRLEN AND COPY FUNCTIONS";
char *test = malloc(strlen(some_text) + 1);
strncpy(test, some_text, strlen(some_text));
strcat(test, "\0");
printf("%s\n", test);
if (test != NULL) free (test);
}
create a
char* some_text
with constant string;create a
char*test
with and allocate memory the size ofsome_text
copy the content of
some_text
totest
concatenate the termination character to
test
print out the
test
free the
test
pointer
If I run this with valgrind
, it says:
==31176== Conditional jump or move depends on uninitialised value(s)
==31176== at 0x4008667: __GI_strlen (mc_replace_strmem.c:404)
==31176== by 0x861DD4: puts (in /lib/libc-2.12.so)
==31176== by 0x80484DF: main (strlen_and_copy.c:13)
The line mentioned in valgrind
output strlen_and_copy.c:13 is below:
printf("%s\n", test);
Is it avoidable or should it be ignored? What is wrong with my code above? Someone please explain.
malloc()
returnedNULL
? \$\endgroup\$