patterncMinor
Conditional jump or move depends on uninitialised value
Viewed 0 times
dependsjumpconditionalvaluemoveuninitialised
Problem
Please review the following code:
-
create a
-
create a
-
copy the content of
-
concatenate the termination character to
-
print out the
-
free the
If I run this with
The line mentioned in
Is it avoidable or should it be ignored? What is wrong with my code above? Someone please explain.
#include
#include
#include
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 of some_text-
copy the content of
some_text to test-
concatenate the termination character to
test-
print out the
test-
free the
test pointerIf 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.
Solution
Some general remarks to your code:
- You should store the string length as a variable rather than calling it multiple times.
- If you do
strncpy(test, some_text, strlen(some_text) + 1)you can get rid of thestrcatasstrncpywill padd the remainder with\0ifsrcis less thanncharacters.
- You don't need to test for
NULLbeforefree
- a) because you'd get a segfault anyway before that line of code if it were
NULL
- b) because the standard guarantees that it is safe to call
free(NULL)
Context
StackExchange Code Review Q#46619, answer score: 8
Revisions (0)
No revisions yet.