Greg01re Greg01re - 29 days ago 9
C Question

Malloc changing another variable's value (char*)

So I'm using the following code, where the function calls looks like this (note the string literal) :

rmv_zeros("288230376151711744000000", '0', '-');


Here is the code:

char* rmv_zeros(char *result, char base_0, char minus)
{
char* formatted;

formatted = malloc(sizeof(char) * (strlen(result) + 1));
if (result[0] == base_0 || (result[1] == base_0 && result[0] == minus))
{
if (if_rmv_zeros_needed(result, formatted, base_0, minus) == char_to_str(base_0))
{
return char_to_str(base_0);
}
else
{
return if_rmv_zeros_needed(result, formatted, base_0, minus);
}
}
else
{
return result;
}
return formatted;
}


The code will not enter in the first
if
statement, hence will go in the
else
(I saw that wile debugging).

But it'll return
2882303761517117440000001
, adding a
'1'
at the very end of result.

However, when I comment the malloc() line (fifth line in this example), the returned value is
288230376151711744000000
, which is the input'd value and logical return.

Any help on this?

Thanks,

EDIT:
Putting
printf("%s\n", result)
at the 3rd line and at the 19th actually ""fixes"" (not the quotes, I know it's not a real fix) the problem. Why?

LPs LPs
Answer

There is only one reason for such a behavior: Undefined Behavior

One main reason can be the leakage of memory you have with malloc into your function. The allocated memory is not freed if the returned memory is not returned by function, in other words if the return result is reached, as in your test case.

So first of all manage it.

char* rmv_zeros(char *result, char base_0, char minus)
{
      char* formatted = NULL;

      if (result[0] == base_0 || (result[1] == base_0 && result[0] == minus))
      {
          formatted = malloc(sizeof(char) * (strlen(result) + 1));
          if (formatted != NULL)
          {
             if (if_rmv_zeros_needed(result, formatted, base_0, minus) == char_to_str(base_0))
               {
                  return char_to_str(base_0);
               }
               else
               {
                  return if_rmv_zeros_needed(result, formatted, base_0, minus);
               }
            }
        }
      else
      {
         return result;
      }
      return formatted;
}

Take a look at your whole code to catch other similar problems.

Comments