我在空闲时间研究一个文件系统,我遇到了一个为指向类型定义结构的指针重新分配内存的问题。file_t:
typedef struct {
char *fileName;
FILE *filePointer;
char *fileContents;
char *filePermissions;
size_t fileSize;
int numFilesUsed;
char *fileOwner;
char *fileGroup;
char *fileCreationDate;
} file_t;
dir_t:
typedef struct {
char **fileNames;
int numFiles;
int *fileSizes;
int dirSize;
file_t *files;
char *path;
} dir_t;
下面是导致分配问题的部分:
dir_t *currentDir = (dir_t*)malloc(sizeof(dir_t));
for(int i = 0; fileLines[i] != NULL; i++){
currentDir->files = (file_t *)realloc(currentDir->files, sizeof(file_t) * (i+2)); // I am using i+2 so that I have space for a null
}
当我编译并运行时,输出是:
EXEC(33314,0x1042f4580) malloc: *** error for object 0x13cf0414a:指针没有被分配EXEC(33314,0x1042f4580) malloc: ***在malloc_error_break中设置断点以调试Abort trap: 6
我最初认为这可能是fileLines[I]没有适当的NULL终止符的问题,导致某种无限循环,但它工作得很好。检查它显示的堆栈上的变量:for循环前:
(char **) fileLines = 0x0000600002900000
(dir_t *) currentDir = 0x0000600000c04000
在循环:I = 0:
(char **) fileLines = 0x0000600002900000
(dir_t *) currentDir = 0x0000600000c04000
则中止信号到达。malloc_error_break:
的程序集libsystem_malloc.dylib`malloc_error_break:
-> 0x184876278 <+0>: pacibsp
0x18487627c <+4>: stp x29, x30, [sp, #-0x10]!
0x184876280 <+8>: mov x29, sp
0x184876284 <+12>: nop
0x184876288 <+16>: ldp x29, x30, [sp], #0x10
0x18487628c <+20>: retab
当前寄存器的内容:
General Purpose Registers:
x0 = 0x0000000000000000
x1 = 0x000000010020c000
x2 = 0x0000000000004000
x3 = 0x0000000184a597aa libsystem_platform.dylib`___lldb_unnamed_symbol3$$libsystem_platform.dylib + 10
x4 = 0x0000000000000000
x5 = 0x0000000000000000
x6 = 0x0000000000000001
x7 = 0x0000000000000000
x8 = 0x0000000010000003
x9 = 0x000000010020c07c
x10 = 0xcccccccccccccccd
x11 = 0x000000000000000a
x12 = 0x0000000000000000
x13 = 0x0000000000000033
x14 = 0x0000000000600000
x15 = 0x0000000000000002
x16 = 0xfffffffffffffff4
x17 = 0x00000001dec1c0f8 (void *)0x0000000184a0bd40: vm_deallocate
x18 = 0x0000000000000000
x19 = 0x0000000000000050
x20 = 0x0000000000000000
x21 = 0x0000000100208028
x22 = 0x000000016fdff5b0
x23 = 0x0000000100208000
x24 = 0x0000000000000000
x25 = 0x0000000000000000
x26 = 0x000000016fdff9df
x27 = 0x000000010007c580 dyld`_main_thread
x28 = 0x0000000000000000
fp = 0x000000016fdff580
lr = 0x0000000184867d50 libsystem_malloc.dylib`malloc_vreport + 428
sp = 0x000000016fdff510
pc = 0x0000000184876278 libsystem_malloc.dylib`malloc_error_break
cpsr = 0x80000000
我在这里没有看到什么?谢谢。
当您用malloc
为currentDir
分配内存时,您没有为currentDir->files
分配任何可指向的内存。因此,您不能realloc
它。
为包含指针成员的结构体分配内存,为指针分配内存,但不为指针指向分配内存。