Reputation: 153
Hi I have to do a simulation of disk for my university.
I got 2 file :
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;
}
I want to write in a file a number of block (here 7), so I do malloc on size of my disk struct and then I do a malloc on diskBlock to make a table d->diskBlock[0].unBlock = malloc(1024); but not for more. how could I do a block[size] with my struct ? (I'm not good in c)
Upvotes: 1
Views: 49
Reputation: 12270
I think you should change this line
d->diskBlock = malloc(1024);
to
d->diskBlock = malloc(sizeof(block) * size);
And, this
d->diskBlock[i].unBlock = malloc(1024);
to
d->diskBlock[i].unBlock = malloc(sizeof(uint8_t) * 4);
Upvotes: 1