0

I have a core dumped and I don't know why. Here is the code:

#include <stdio.h>

int str_size(char *str) {
    int size = 0;

    for (int i = 0 ; str[i] != '\0' ; i++) {
    size++;
    }
    return (size);
}

int find_char(char c, char *str) {
    int place = 0;
    for (int i = 0 ; str[i] != '\0' ; i++) {
        if (c == str[i]) {
            place = i;
        }
    }
    return (place);
}

char *convert_dec_to_base(int n, char *base) {
    char n_based[64];
    char converted_b[64];

    for (int i = 0 ; n != 0 ; i++) {
        n_based[i] = base[n % str_size(base)];
        n /= str_size(base);
    }
    for (int i = 0 ; i < str_size(n_based) ; i++) {
        converted_b[str_size(n_based) - i - 1] = n_based[i];
    }
    return (converted_b);
}
int main(void) {
    printf("%s\n", convert_dec_to_base(32, "0123456789ABCDEF"));
    printf("%c\n", t[1]);
    return (0);
}

This code will convert a decimal integer into a given base. It will return a char* containing the base transformed integer.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
pulk66
  • 11
  • In `convert_dec_to_base()` you return the local array `converted_b` (well, you return a pointer to its first element), but the array no longer exists by the time `main()` gets to using it (the array only exists while the function is *active*). – pmg Jun 26 '20 at 17:28
  • _Side note:_ `t` is undeclared – Craig Estey Jun 26 '20 at 17:29
  • It doesn't look like `converted_b` is null terminated – 001 Jun 26 '20 at 17:29
  • _Side note:_ If `find_char` fails, it returns 0. This is a _valid_ index into the string (e.g. if the first char of `str` _is_ `c`, this returns 0 also). Adjust the function to return (e.g.) -1 if the char is _not_ found. – Craig Estey Jun 26 '20 at 17:34

1 Answers1

1

converted_b is a variable local to the function, returning it results in undefined behavior, you can declare it as a pointer and allocate memory in order to be able to return it:

#include <stdlib.h>
char* converted_b = malloc(64);

In this case the program will end there, but in a normal situation, when you are finished using it, you should then free the memory previously allocated:

char* str = convert_dec_to_base(32, "0123456789ABCDEF");
printf("%s\n",str);
free(str);

As an alternative, as @CraigEstey mentioned in the comment section you can use static storage:

static char converted_b[64];

This will ensure the lifetime of the variable is the same as the program itself.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 1
    Note that, as `main` uses the result, it doesn't `free` it, and produces a memory leak. Perhaps using `static` as an alternative, or more explanation about using `free`? – Craig Estey Jun 26 '20 at 17:31