由于在 C 中打开新文件而导致数据损坏
Data corruption due to opening a new file in C
我有以下代码,其中,我 return 一个指针的内存地址,我在该指针的位置存储了一个字符串。
代码看起来像这样:
char* segs[1];
segs[0] = (char *) myfunction("name", 100);
//myfunction(Name,size of the memory to be allocated)
FILE *write_log;
write_log = fopen(redo_path,"a+");
函数myfunction return是一个内存位置,固定为segs[0]的基地址。
我的内存分配是这样的:
FILE *fp_seg;
fp_seg = fopen(compare,"r");
//maps from disk to mem
void *p;
p = (void *)malloc(size_to_create); //Mapping
int c;
c = fread(p,size_to_create,1,fp_seg);
我们在磁盘上打开一个文件,并生成文件中第一个位置的地址对应映射。 (p 更多是对文件中第一个位置的引用)。
问题:
使用 write_log 文件指针打开现有文件会损坏存储在内存位置 segs[0] 的字符串的内容。在调试时,我发现文件跨越的内存区域和段[0]重叠,即
segs[0]
的内存位置为 0x1cc5de0
并存储在 "Hello, world"
。
write_log
的内存位置为 0x1cc5d50
我的猜测是在该位置打开文件会破坏 seg[0]
的内容。
如何解决这个问题?有没有办法分配内存使区域不重叠?
编辑:
我的功能是这样的:
myfunction(char * compare, int size_to_create)
{
//size_to_create is the size of the memory we want to allocate to seg[0]
//Create a file with the name compare in the disk
FILE *fp_seg;
fp_seg = fopen(compare,"r");
//Read the file (File has no content as of now)
void *p;
p = (void *)malloc(size_to_create); //p has an address in main memory
int c;
c = fread(p,size_to_create,1,fp_seg);
void *t;
t=p;
//Future reads will have the same mapping
free(p);
}
问题在于指针 p 的释放,这会释放内存。
这样就没有限制系统不把p原来指向的区域分配给另外一段代码申请内存了
我有以下代码,其中,我 return 一个指针的内存地址,我在该指针的位置存储了一个字符串。 代码看起来像这样:
char* segs[1];
segs[0] = (char *) myfunction("name", 100);
//myfunction(Name,size of the memory to be allocated)
FILE *write_log;
write_log = fopen(redo_path,"a+");
函数myfunction return是一个内存位置,固定为segs[0]的基地址。 我的内存分配是这样的:
FILE *fp_seg;
fp_seg = fopen(compare,"r");
//maps from disk to mem
void *p;
p = (void *)malloc(size_to_create); //Mapping
int c;
c = fread(p,size_to_create,1,fp_seg);
我们在磁盘上打开一个文件,并生成文件中第一个位置的地址对应映射。 (p 更多是对文件中第一个位置的引用)。
问题:
使用 write_log 文件指针打开现有文件会损坏存储在内存位置 segs[0] 的字符串的内容。在调试时,我发现文件跨越的内存区域和段[0]重叠,即
segs[0]
的内存位置为 0x1cc5de0
并存储在 "Hello, world"
。
write_log
的内存位置为 0x1cc5d50
我的猜测是在该位置打开文件会破坏 seg[0]
的内容。
如何解决这个问题?有没有办法分配内存使区域不重叠?
编辑: 我的功能是这样的:
myfunction(char * compare, int size_to_create)
{
//size_to_create is the size of the memory we want to allocate to seg[0]
//Create a file with the name compare in the disk
FILE *fp_seg;
fp_seg = fopen(compare,"r");
//Read the file (File has no content as of now)
void *p;
p = (void *)malloc(size_to_create); //p has an address in main memory
int c;
c = fread(p,size_to_create,1,fp_seg);
void *t;
t=p;
//Future reads will have the same mapping
free(p);
}
问题在于指针 p 的释放,这会释放内存。
这样就没有限制系统不把p原来指向的区域分配给另外一段代码申请内存了