Reputation: 97
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?
Upvotes: 0
Views: 1809
Reputation: 1
variable(char *) whose value is changing you can allocate it memory using calloc function because calloc will give contiguous block of memory and now if you use malloc, it will not give the already allocated addresses.
Upvotes: 0
Reputation: 16223
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 free
d 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, otherwise, after some time of execution, malloc
can fail.
If all parts of your code does not take care of malloc
return value, as shown in your code, the pointer passed to result can be invalid (in other words == NULL
)
Into your function you can simply manage the malloc
as below, but remember that the caller must menage the free of the allocated memory.
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.
Upvotes: 1