简体   繁体   English

不一致的malloc内存损坏

[英]Inconsistent malloc memory corruption

I'm currently writing a method that reads from an allocated block of memory and prints out its contents from a certain offset and up to a specified size, both of which are passed as parameters. 我当前正在编写一个方法,该方法从分配的内存块中读取并从特定偏移量打印输出其内容,直到指定大小为止,两者均作为参数传递。 I'm using char pointers to accomplish this, but keep getting a malloc error around line 我正在使用char指针来完成此操作,但是在行周围不断出现malloc错误

char *content = (char *)malloc(size+1);

Code for the method: 该方法的代码:

int file_read(char *name, int offset, int size)
{
    //First find file and its inode, if existing
    int nodeNum = search_cur_dir(name);
    if(nodeNum < 0) {
            printf("File read error: file does not exist\n");
            return -1;
    }

    //Size check, to avoid overflows/overreads
    if(offset > inode[nodeNum].size || size > inode[nodeNum].size || (offset+size) > inode[nodeNum].size)   {
            printf("File read error: offset and/or size is too large\n");
            return -1;
    }

    int i, read_size, track_size = size, content_offset = 0;
    int target_block = offset / BLOCK_SIZE; //Defined as constant 512
    int target_index = offset % BLOCK_SIZE;


    char *raw_content = (char *)malloc(inode[nodeNum].size+1);
    printf("check1\n"); //Debug statment

    for(i = target_block; i < (inode[nodeNum].blockCount-(size/BLOCK_SIZE)); i++)   {
            disk_read(inode[nodeNum].directBlock[i], raw_content+content_offset);
            content_offset += BLOCK_SIZE;
    }

    printf("check2\n"); //Debug statment
    char *content = (char *)malloc(size+1);

    memcpy(content, raw_content+target_index, size);
    printf("%s\n", content);
    free(raw_content);
    free(content);
    return 0;

}

and code for disk_read: 和disk_read的代码:

char disk[MAX_BLOCK][BLOCK_SIZE]; //Defined as 4096 and 512, respectively
int disk_read(int block, char *buf)
{
                if(block < 0 || block >= MAX_BLOCK) {
                                printf("disk_read error\n");
                                return -1;
                }
                memcpy(buf, disk[block], BLOCK_SIZE);

                return 0;
}

structure for node 节点的结构

typedef struct {
                TYPE type;
                int owner;
                int group;
                struct timeval lastAccess;
                struct timeval created;
                int size;
                int blockCount;
                int directBlock[10];
                int indirectBlock;
                char padding[24];
} Inode; // 128 byte

The error I get when using this method is one of memory corruption 使用此方法时出现的错误是内存损坏之一

*** glibc detected *** ./fs_sim: malloc(): memory corruption (fast): 0x00000000009f1030 ***

Now the strange part is, firstly this only occurs after I have used the method a few times - for the first two or three attempts it will work and then the error occurs. 现在奇怪的是,首先这只会在我使用该方法几次后才会发生-对于前两到三次尝试它将起作用,然后发生错误。 For instance, here is an example test run: 例如,这是一个示例测试运行:

% read new 0 5
z12qY

% read new 0 4
z12q

% read new 0 3
*** glibc detected *** ./fs_sim: malloc(): memory corruption (fast): 0x00000000009f1030 ***

Even stranger still, this error disappears completely when I comment out 即使是陌生人,当我注释掉时,该错误也将完全消失

free(raw_content);
free(content);

Even through this would tie up the memory. 即使这样也会占用内存。 I've read through previous posts regarding malloc memory corruption and understand this usually results from overwriting memory bounds or under allocating space, but I can't see where I could be doing this. 我已经阅读了有关malloc内存损坏的以前的文章,并了解这通常是由于覆盖内存界限或分配空间不足而导致的,但是我看不到该在哪里进行操作。 I've attempted other sizes for malloc as well and these produced the best results when I commented out the lines freeing both pointers. 我也尝试了其他大小的malloc,当我注释掉释放两个指针的行时,它们产生了最佳结果。 Does anyone see what I could be missing? 有人看到我可能会想念的吗? And why does this occur so inconsistently? 为什么会如此不一致地发生呢?

Code allocates space for characters and a null character, but does not insure the array is terminated with a null character before printing as a string. 代码为字符和空字符分配空间,但是不能确保在打印为字符串之前以空字符终止数组。

char *content = (char *)malloc(size+1);
memcpy(content, raw_content+target_index, size);

// add
content[size] = '\0';

printf("%s\n", content);

Likely other issues too. 可能还有其他问题。

[Edit] [编辑]

OP code is prone to mis-coding and dependent on inode[] to have coherent values ( .blockCount . size ). OP码是容易发生误编码和依赖于inode[]为具有相干值( .blockCount . size )。 Clarify and simplify by determining the loop count and allocating per that count. 通过确定循环计数并按该计数分配来澄清和简化。

int loop_count = (inode[nodeNum].blockCount-(size/BLOCK_SIZE)) - target_block;
char *raw_content = malloc(sizeof *raw_content * loop_count * BLOCK_SIZE);
assert(raw_count);
for (loop = 0; loop < loop_count; loop++) {
   i = target_block + loop;
   disk_read(inode[nodeNum].directBlock[i], raw_content + content_offset);
   content_offset += BLOCK_SIZE;
}

Also recommend checking the success of disk_read() 还建议检查disk_read()是否成功

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM