2016-11-06 57 views
0

我不明白为什么我要在free_memory函数内部发生分段错误。下面是程序:不能理解这个错误,同时释放内存中的内存C

#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; 
} 

调试器显示该消息有关错误:

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 

我希望有人能帮助我,我不明白为什么我访问一个坏的指针。

+0

(HTTP [从标准使用与fgets()读取]的可能重复: //stackoverflow.com/questions/40412010/reading-from-stdin-using-fgets) –

回答

1

你是不是修改你的maincellsallocate_memory设置。您正在修改副本。

如果你想在一个函数修改的指针,你有一个指针到指针传递给函数:

... 

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本身,你需要或者

  • 指针传递给它,或
  • 收益新分配的指针,并将其存储回cellsmain()

    否则,allocate_memory()函数中的cells函数是本地的,因为一旦您从该函数返回,对cells所做的任何更改都将丢失。

其结果是,里面free_memory()功能,接入cells[i]是无效的,因为cells没有指向任何有效的内存,在所有。尝试访问无效内存调用undefined behavior

0

分配函数不返回新分配的块。 allocate_memory(cells);

外部效果就好像细胞没有被功能(之前设置为NULL)