c程序中的free()错误

时间:2017-12-07 00:29:06

标签: c free

我似乎在sfs_fread方法中继续获取free()无效指针,无效大小或双重释放/损坏错误:

int sfs_fread(int fileID, char *buf, int length) {
int bytesRead = 0;
int bytesToRead = length;
int inodeInd = fileDescriptorTable[fileID].inodeIndex;
int indirectTable[256]; 
if(inodeInd == -1){
    printf("File with fileID %i is not open, can't read",fileID);
    return -1;
}
if(length < 1 ){
    printf("Invalid length specified (Length too small or too big)\n");
    return -1;
}
//if specified length > size of file, change bytes to read to be the difference between size and read write pointer
if(fileDescriptorTable[fileID].rwptr + length > inodeTable[inodeInd].size){
    bytesToRead = inodeTable[inodeInd].size - fileDescriptorTable[fileID].rwptr;
}
while(bytesToRead > 0){
    int currentReadLength = 0;
    int dataPointerIndex = fileDescriptorTable[fileID].rwptr/BLOCK_SIZE;
    //if we only need to read from direct data pointer block currently
    if(dataPointerIndex < 12){
        temp = calloc(1,BLOCK_SIZE);
        count = read_blocks(inodeTable[inodeInd].data_ptrs[dataPointerIndex],1,temp);
        if(count < 0){
            printf("Error reading data\n");
        }
        //append available data from current block to buffer based on number of bytes read, and current rwptr in current block
        currentReadLength = BLOCK_SIZE - (fileDescriptorTable[fileID].rwptr % BLOCK_SIZE);
        memcpy(buf + bytesRead,temp + (fileDescriptorTable[fileID].rwptr % BLOCK_SIZE),currentReadLength);
        free(temp);
        //increment rwptr and update temp variables
        fileDescriptorTable[fileID].rwptr += currentReadLength;
        bytesToRead -= currentReadLength;
        bytesRead += currentReadLength; 
        dataPointerIndex++; 
    }
    //if we need to read from indirect pointer block
    else{
        //read indirect pointer block into stack
        temp = calloc(1,sizeof(indirectTable));
        count = read_blocks(inodeTable[inodeInd].indirectPointer,1,temp);
        if(count < 0){
            printf("Error reading indirect pointer table\n");
        }
        memcpy(indirectTable,temp,sizeof(indirectTable));
        free(temp);

        //read data block pointed to by indirect table index,
        temp = calloc(1,BLOCK_SIZE);
        count = read_blocks(indirectTable[dataPointerIndex-12],1,temp);
        if(count < 0){
            printf("Error reading indirect pointer data\n");
        }
        currentReadLength = BLOCK_SIZE - (fileDescriptorTable[fileID].rwptr % BLOCK_SIZE);
        memcpy(buf + bytesRead,temp + (fileDescriptorTable[fileID].rwptr % BLOCK_SIZE),currentReadLength);
        free(temp);
        fileDescriptorTable[fileID].rwptr += currentReadLength;
        bytesToRead -= currentReadLength;
        bytesRead += currentReadLength; 
        dataPointerIndex++; 
    }
}

return bytesRead;

}

测试代码使用随机数发生器,导致三种不同的错误。我没有看到双重释放,temp是一个void *全局变量。我试过调试无济于事但我知道问题在于这个方法,因为在评论之后它完成了运行。在此先感谢您的帮助。

0 个答案:

没有答案