2016-11-06 7 views
0

free_memory 함수 내에서 세분화 오류가 발생하는 이유를 알지 못합니다. 여기에 프로그램입니다 :C에서 메모리를 해제하는 동안이 오류를 인식 할 수 없음

Process 1433 launched: '/Users/Jaime/Documents/workspaceC/PruebasC/PruebasC/sk' (x86_64) 
Allocated 
Process 1433 stopped 
* thread #1: tid = 0x1058a, 0x0000000100000e95 sk`free_memory + 37, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0) 
    frame #0: 0x0000000100000e95 sk`free_memory + 37 
sk`free_memory: 
-> 0x100000e95 <+37>: movq (%rcx,%rax,8), %rdi 
    0x100000e99 <+41>: callq 0x100000f20    ; symbol stub for: free 
    0x100000e9e <+46>: movl -0xc(%rbp), %eax 
    0x100000ea1 <+49>: addl $0x1, %eax 

은 내가 나쁜 포인터를 액세스하고 왜하지 않는, 누군가가 나를 도울 수 있기를 바랍니다 :

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

void allocate_memory (char **cells) 
{ 
    int i; 

    cells = (char **) malloc(9 * sizeof(char *)); 
    if (cells == NULL) 
    { 
     perror("Couldn't allocate memory"); 
     exit(1); 
    } 

    for (i = 0; i < 9; i++) 
    { 
     cells[i] = (char *) malloc(9 * sizeof(char)); 
     if (cells[i] == NULL) 
     { 
      perror("Couldn't allocate memory"); 
      exit(1); 
     } 

     memset(cells[i], 1, 9); 
    } 
} 

void free_memory (char **cells) 
{ 
    int i; 

    for (i = 0; i < 9; i++) 
    { 
     free(cells[i]); 
    } 

    free(cells); 
} 

int main (int argc, char *argv[]) 
{ 
    char **cells = NULL; 

    allocate_memory(cells); 
    printf("Allocated\n"); 
    free_memory(cells); 

    return 0; 
} 

디버거 오류에 대한이 메시지를 보여줍니다.

+0

가능한 중복 : //stackoverflow.com/questions/40412010/reading-from-stdin-using-fgets) –

답변

1

에 의해 설정되지 않은 것처럼

외부 효과이다. 복사본을 수정 중입니다.

당신이 함수에 대한 포인터를 수정하려면, 당신은 함수에 대한 포인터 - 투 - 포인터를 전달해야한다 : (HTTP [사용는 fgets()를 표준 입력 읽기]의

... 

void allocate_memory (char ***cells) 
{ 
    int i; 

    *cells = (char **) malloc(9 * sizeof(char *)); 
    if (*cells == NULL) 
    { 
     perror("Couldn't allocate memory"); 
     exit(1); 
    } 

    for (i = 0; i < 9; i++) 
    { 
     (*cells)[i] = (char *) malloc(9 * sizeof(char)); 
     if ((*cells)[i] == NULL) 
     { 
      perror("Couldn't allocate memory"); 
      exit(1); 
     } 

     memset((*cells)[i], 1, 9); 
    } 
} 

...  

int main (int argc, char *argv[]) 
{ 
    char **cells = NULL; 

    allocate_memory(&cells); 

    ... 
} 
+0

감사! 정말 좋은 대답 사람 : D 조 –

0

C는 함수 인수 전달에 대한 값 별 전달을 사용합니다. 혹시 cells 자체 메모리를 할당 할, 당신도

  • 그것에 대한 포인터를 전달해야하거나
  • 반환 새로 할당 된 포인터를하고 main()에 다시 cells에 저장합니다.

    allocate_memory() 기능의 cells은 해당 기능에서 돌아 오면 cells에 대한 변경 사항이 모두 손실된다는 점에서 로컬입니다. cells 전혀 어떠한 유효한 메모리 가리 키지 않는 한 결과

free_memory() 함수 내부 액세스 cells[i]은 무효이다. 유효하지 않은 메모리에 액세스하려고 시도하면 undefined behavior이 호출됩니다.

0

할당 기능은 새로 할당 된 블록을 반환하지 않습니다. allocate_memory (cells); 세포가 당신은 당신의 maincellsallocate_memory에서 수정되지 않습니다 (이전에 NULL로 설정) 기능