简体   繁体   中英

AddressSanitizer: attempting free on address which was not malloc()-ed:

Why does my code give AddressSanitizer error (ie attempting to free on address which was not malloc-ed)? I did calloc new memory, but when I attempt to free them, I'll run into an error? Any form of help or advice would be appreciated, thank you!

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
    char name[100];
    char gender; // 'M' for Male, 'F' for Female
} person;
bool not_in_arr(char *name, char **arr, int size) {
    for (int i = 0; i < size; i++) {
        if (strcmp(name, arr[i]) == 0) {
            return false;
        }
    }
    return true;
}
char **get_lucky_ones(person table[], int n, int *r_size) {
    person *new = calloc(n * 2, sizeof(person));
    for (int i = 0; i < n; i++) {
        new[i] = table[i];
        new[n + i] = table[i];
    }
    char **new_arr = calloc(n, sizeof(char *));
    int index = 0;
    for (int i = 1; i < 2 * n - 1; i++) {
        char gender = new[i].gender;
        if (new[i + 1].gender != gender &&new[i - 1].gender != gender) {
            char *name = new[i].name;
            if (not_in_arr(name, new_arr, index)) {
                new_arr[index] = name;
                //printf("%s\n", new_arr[index]);
                index++;
            }
        }
    }
    *r_size = index;
    //free(new);
    return new_arr;
}
int main(void) {
    {
        person table[] = {{"apple", 'M'}, {"berry", 'F'}, {"cherry", 'F'},

                          {"durian", 'M'},
                          {"fig", 'F'}};

        int r_size;
        char **result = get_lucky_ones(table, sizeof(table) / sizeof(table[0]),
                                       &r_size);
        for (int i = 0; i < r_size; i++) {
            printf("%s ", result[i]);
            free(result[i]);
        }
        free(result);
        printf("\n");
    }
   
}

new_arr points at the memory allocated by the new array. So if you free() new , then new_arr points at garbage. Maybe you want to make a hardcopy here: new_arr[index] = name; .

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