2017-05-11 4 views
1

다음 구조로 ok라는 단일 구조체에 g_new()를 사용하여 메모리를 할당했습니다. glib의 메모리 할당 사용하기 g_new()

/*Structure*/ 
typedef struct 
{ 
    guint16 index; 
    gchar * date; 
    gchar * number; 
}h_item; 

/*allocation*/ 
h_item * my_h_item = g_new(h_item, 1); 

/*freeing function*/ 
void free_h_item(h_item * item) 
{ 
    g_free(item->date); 
    g_free(item->number); 
    g_free(item); 
} 

는 이제 배열 [2] 구조체, 예를 들어 정적으로 할당이 같다 위해 동일한 작업을 수행하려고하지만 그것이 프로그램 스택에있어 의미 할 것입니다.

h_item my_h_item[5]; 

내가 동적 같은 위를 할당하고 싶지만, 내가 프로그램을 실행 문제를 갖고있는 것 같다 ...

/*Structure*/ 
typedef struct 
{ 
    guint16 index; 
    gchar * date; 
    gchar * number; 
}h_item; 


/*freeing function*/ 
void free_h_item(h_item * item) 
{ 
    g_free(item->date); 
    g_free(item->number); 
    g_free(item); 
} 

static h_item * my_h_item[2]; 

int main() 
{ 
    /*allocation*/ 
    my_h_item[2] = g_new(h_item, 2); 

    my_h_item[0]->date = g_strdup("12345"); /*Test*/ 
    return 0; 
} 

이 프로그램은 세그먼테이션 폴트 (segfault)를 제외한 컴파일 ...

#0 0x00000000004007a7 in main() at struct_memory.c:30 
30  my_h_item[0]->date = g_strdup("12345"); /*Test*/ 

할당량이 잘못되었습니다.

+0

'my_h_item [2] = g_new (h_item, 2);'아웃 바운드 액세스. –

답변

2

당신은 my_h_item [2] 당신이 my_h_item을 accesing된다 [0]

을 할당하지 않는 당신은 my_h_item를 할당 할 필요가 할당 된 [0] 요소를

my_h_item을 사용하는 것뿐만 아니라 이전에 [2] my_h_item [0] 및 my_h_item [1] 만 유효하다는 이유로 my_h_item은 유효하지 않습니다.

+0

사실, 내가 그 대답에 추가했습니다 – Pras

2

2 개의 구조체 배열을 만들고 싶다고 말했습니까? 작성한 것은 두 개의 포인터로 이루어진 배열입니다. 당신이해야 할 일은

static h_item * my_h_item; 

이며 다음

h_item = g_new(h_item, 2); 

그런 다음 h_item[0]h_item[1] 같은 두 구조체 및

h_item[0].data = g_strdup(...); 

로 그 안에 날짜를 사용할 수 있습니다 또한 g_ * 함수 클래스는 비표준입니다. malloc을 사용하고 무료로 사용하십시오.

+0

고마워 ... 경계 밖으로 [2] 통지하지 않았다. –

+0

@NatenBaptista는 실제로 문제가 아니지만. 포인터가 필요할 때 포인터 배열을 선언했습니다. –