1

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)

12
  • 1. Alaways check the return value of malloc() against NULL. 2. Why this d->diskBlock = malloc(1024);? it should be malloc(size * sizeof(block));! Commented Jan 10, 2016 at 14:09
  • why d->diskBlock = malloc(1024);? Don't use magic numbers. Commented Jan 10, 2016 at 14:09
  • I want that uint8_t *unBlock = malloc(1024); Commented Jan 10, 2016 at 14:12
  • When you're doing d->diskBlock = malloc(1024) you allocate 1024 bytes not 1024 block structures. While it may not be the cause of your crash, it is a problem. Commented Jan 10, 2016 at 14:13
  • 1
    This fwrite(&d->diskBlock[i],1024,1,f); seems to be the problem, what are you trying with it? Commented Jan 10, 2016 at 14:13

1 Answer 1

1

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

But I don't thikn this is triggering SIGSEGV. 1024 is enough space, more than enough. It would need maximum 7 * sizeof(block) or 56B approximately assuming 64 bit pointers.
And how could I have a malloc(1024) on my block ? I need block[1024] length to simulate a disk.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.