gpt4 book ai didi

C - 段错误 : 11

转载 作者:行者123 更新时间:2023-11-30 15:13:18 25 4
gpt4 key购买 nike

嗨,我必须为我的大学进行磁盘模拟。

我有 2 个文件:

tttfs.h:

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

typedef struct _disk disk;
typedef struct _block block;

struct _block{
uint8_t *unBlock;
};

struct _disk{
int id;
block *diskBlock;
};

tfs_create.c:

#include "tttfs.h"

uint8_t little[4];

int tttfs_create(int size, char *name);
void inttolitend(uint32_t x, uint8_t* lit_int);

int main(){
tttfs_create(7, "disk.tfs");
}

int tttfs_create(int size, char *name){
FILE *f = NULL;
if ((f = fopen(name, "wb"))!=NULL)
{
disk *d = malloc(sizeof(disk));
d->diskBlock = malloc(1024);
d->id = 1;
int i;
for(i = 0; i<size; i++){
printf("%d\n", i);
d->diskBlock[i].unBlock = malloc(1024); //I got the segmentation fault here
}
inttolitend(size, little);
for(i = 0; i<4; i++){
d->diskBlock[0].unBlock[i] = little[i];
}
for(i = 0; i<size; i++){
fwrite(&d->diskBlock[i],1024,1,f);
}
}
else
printf("Erreur\n\n");
return 0;
}

void inttolitend(uint32_t x, uint8_t* lit_int){
lit_int[3] = (uint8_t)x / (256*256*256);
lit_int[2] = (uint8_t)(x % (256*256*256)) / (256*256);
lit_int[1] = (uint8_t)((x % (256*256*256)) % (256*256)) / 256;
lit_int[0] = (uint8_t)((x % (256*256*256)) % (256*256)) % 256;
}

我想在文件中写入多个 block (此处为 7),因此我对磁盘结构的大小进行 malloc,然后对 diskBlock 进行 malloc 以创建表 d->diskBlock[0].unBlock = malloc(1024);但不是为了更多。我怎样才能用我的结构做一个 block [size]? (我不太擅长c)

最佳答案

我认为你应该改变这一行

d->diskBlock = malloc(1024);

d->diskBlock = malloc(sizeof(block) * size);
<小时/>

还有,这个

d->diskBlock[i].unBlock = malloc(1024);

d->diskBlock[i].unBlock = malloc(sizeof(uint8_t) * 4);

关于C - 段错误 : 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com