Tại sao con trỏ xuất ra giá trị rác

Mình có code sau.

// Assignment.cpp
struct position {
    int x;//row
    int y;//column
};

void print_position(struct position pos) {
    printf("(%d, %d) ", pos.x, pos.y);
}

void print_lst_position(struct position* lst_pos, int size) {
    int i = 0;
    while(i < size) {
        print_position(lst_pos[i]);
        i++;
    }
}

struct position* generate_list(int** board_state, int *size) {

    struct position lst[4];
    *size = 4;
    //assigning values
    lst[0].x = 2;
    lst[0].y = 3;

    lst[1].x = 3;
    lst[1].y = 2;

    lst[2].x = 4;
    lst[2].y = 5;

    lst[3].x = 5;
    lst[3].y = 4;

    return lst;
}

//main.cpp
int main() {
    struct position *test;
    int ** a;
    int size;
    int i;
    a = (int**)malloc(8 * sizeof(int*));
    for ( i = 0; i < 8; ++i)
        a[i] = (int*) malloc(8 * sizeof(int)) ;

    test = generate_list(a, &size);
    print_lst_position(test, size);

    _getch();
    return 0;
}

Cho mình hỏi sao khi chạy nó lại xuất ra các giá trị rác.

Mình chạy in ra

(2, 3) (3, 2) (4, 2) (5, 4)

Sao em chạy lại in ra (-858993460, -858993460) 4 cái y chang nhau vậy.

@ndd44 dùng compiler hay IDE nào để biên dịch?

Em dùng visual studio 2013

Lỗi nằm ở hàm generate_list, sửa lại như sau

struct position* generate_list(int** board_state, int *size) {

    struct position* lst;
    lst = (struct position *) malloc (4 * sizeof(struct position));
    *size = 4;
    //assigning values
    lst[0].x = 2;
    lst[0].y = 3;

    lst[1].x = 3;
    lst[1].y = 2;

    lst[2].x = 4;
    lst[2].y = 5;

    lst[3].x = 5;
    lst[3].y = 4;

    return lst;
}

mà chương trình này quên hủy bộ nhớ nhé, nhớ tìm hết các nơi malloc mà delete hết đi. Ví dụ như hàm này sau khi xài xong ở cuối chương trình phải hủy vùng nhớ này đi.

OK cảm ơn anh, em đang test nên quên xoá vùng nhớ. Mà cho em hỏi sao cái lst em dùng mảng tĩnh thì nó lại ra giá trị rác vậy.

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?