我正在尝试用C创建一个文件系统。当我在下面的代码中打印我的值时,我的代码部分出了问题:
for (int i = 0; i<NUM_POINTERS; i++) {
printf("before SB->root[%d]=%d\n", i, SB->root->pointers[i]);
}
write_blocks(0, 1, SB);
for (int i = 0; i<NUM_POINTERS; i++) {
printf("after SB->root[%d]=%d\n", i, SB->root->pointers[i]);
}
我的write_blocks方法:
int write_blocks(int start_address, int nblocks, void *buffer)
{
int i, e, s;
e = 0;
s = 0;
void* blockWrite = (void*) malloc(BLOCK_SIZE);
/*Checks that the data requested is within the range of addresses of the disk*/
if (start_address + nblocks > MAX_BLOCK)
{
printf("out of bound error\n");
return -1;
}
/*Goto where the data is to be written on the disk*/
fseek(fp, start_address * BLOCK_SIZE, SEEK_SET);
/*For every block requested*/
for (i = 0; i < nblocks; ++i)
{
/*Pause until the latency duration is elapsed*/
usleep(L);
memcpy(blockWrite, buffer+(i*BLOCK_SIZE), BLOCK_SIZE);
fwrite(blockWrite, BLOCK_SIZE, 1, fp);
fflush(fp);
s++;
}
free(blockWrite);
/*If no failure return the number of blocks written, else return the negative number of failures*/
if (e == 0)
return s;
else
return e;
}
以下是打印的内容:
在SB-&gt; root [0] = 1 之前
在SB-&gt; root [1] = 2
之前在SB-&gt; root [2] = 3
之前在SB-&gt; root [3] = 4
之前在SB-&gt; root [4] = 5
之前 在SB-&gt; root [5] = 6 之前在SB-&gt; root [6] = 7
之前在SB-&gt; root [7] = 8
之前
在SB-&gt; root [8] = 9
之前在SB-&gt; root [9] = 10
之前 在SB-&gt; root [10] = 11 之前在SB-&gt; root [11] = 12
之前在SB-&gt; root [12] = 13
之前在SB-&gt; root [13] = 14
之前在SB-&gt; root [0] = 1234344888
之后在SB-&gt; root [1] = 32688
之后在SB-&gt; root [2] = 3
之后在SB-&gt; root [3] = 4
之后在SB-&gt; root [4] = 5
之后在SB-&gt; root [5] = 6
之后在SB-&gt; root [6] = 7
之后在SB-&gt; root [7] = 8
之后
在SB-&gt; root [8] = 9
之后 在SB-&gt; root [9] = 10 之后在SB-&gt; root [10] = 11
之后在SB-&gt; root [11] = 12
之后在SB-&gt; root [12] = 13
之后在SB-&gt; root [13] = 14
之后
我不明白为什么我的第一个和第二个指针值会发生变化?
一些额外的信息:SB是超级块,这是我的结构:
typedef struct iNode
{
int id;
int size;
int pointers[NUM_POINTERS];
} iNode;
typedef struct superBlock
{
int magic_number;
int block_size;
int num_blocks;
int num_inodes;
iNode *root;
iNode jNodes[20];
} superBlock;
答案 0 :(得分:1)
这是单线程吗? 修改后的SB-&gt; root [0,1]是否包含您要写入的数据? 什么是BLOCK_SIZE?
我怀疑问题不在write_blocks()之外。我最好的猜测是你不小心把某个地方的SB释放了,而malloc给你的地址相同。在malloc检查(打印或调试器)后,缓冲区和blockWrite都确保它们不同且有效。
无关的问题: