简体   繁体   中英

How can I trace a core dump in my C code?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM