opendir 函数损坏目录名称
我在使用 C 语言中的 opendir
函数时遇到问题。代码如下:
Declaration of rvm
:
rvm_t func()
{
rvmBlock=(rvm_t)malloc(sizeof(rvm_t));
return rvmBlock;
}
rvm_t rvm;
rvm=func();
printf("rvm->backingStore=%s\n", rvm->backingStore);
if( (dir = opendir(rvm->backingStore)) !=NULL )
{
printf("rvm->backingStore inside if=%s\n", rvm->backingStore);
}
我得到的输出是:
rvm->backingStore=rvm_segments/
rvm->backingStore inside if=rvm_segments!?
"!? "
是一些由于某种原因出现的垃圾字符。
有人可以解释一下出了什么问题吗?
这是rvm结构:
struct rvm_info
{
char backingStore[20];
struct memSeg * memSegs[20];
long int storage_size;
int memSeg_count;
FILE * log_fd;
};
typedef struct rvm_info* rvm_t;
I am having a problem with the opendir
function in C. Here is the code:
Declaration of rvm
:
rvm_t func()
{
rvmBlock=(rvm_t)malloc(sizeof(rvm_t));
return rvmBlock;
}
rvm_t rvm;
rvm=func();
printf("rvm->backingStore=%s\n", rvm->backingStore);
if( (dir = opendir(rvm->backingStore)) !=NULL )
{
printf("rvm->backingStore inside if=%s\n", rvm->backingStore);
}
The output i am getting for this is:
rvm->backingStore=rvm_segments/
rvm->backingStore inside if=rvm_segments!?
"!?"
are some garbage characters that are appearing for some reason.
Can someone explain what is going wrong.
Here is the rvm structure:
struct rvm_info
{
char backingStore[20];
struct memSeg * memSegs[20];
long int storage_size;
int memSeg_count;
FILE * log_fd;
};
typedef struct rvm_info* rvm_t;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您的问题:
rvm_t
被定义为指向struct rvm_info
的指针,因此您将错误的大小传递给malloc
。sizeof(rvm_t)
等于指针的大小(通常为 4 或 8 字节),而不是struct rvm_info
的大小(远远超过 4 或 8 字节) 。您希望大小是 struct rvm_info 的大小,而不是指针。将该调用更改为:这意味着:
否则,您将导致未定义的行为,因为您没有为整个 struct rvm_info 分配足够的内存。因此,您将将该字符串存储在尚未分配给 rvm 的内存部分中,并且程序的任何其他部分都可以分配该内存。
碰巧调用
opendir
会导致堆上的一些内存被修改,它不会直接/故意修改传递给它的字符串,特别是因为参数的类型为const char*
。编辑:正如 Keith 在评论中提到的,当使用 C(不是 C++)时,转换
malloc
的结果可能被认为是不好的。 此问题对此主题进行了讨论。This is your problem:
rvm_t
is defined as a pointer to astruct rvm_info
, therefore you're passing an incorrect size tomalloc
.sizeof(rvm_t)
equates to the size of a pointer (usually 4 or 8 bytes) and NOT the size of astruct rvm_info
(which is well over 4 or 8 bytes). You want the size to be that ofstruct rvm_info
, NOT a pointer. Change that call to:Which just means:
Otherwise, you're causing undefined behaviour since you haven't allocated enough memory for a whole
struct rvm_info
. Therefore you'll be storing that string in a part of memory that hasn't been allocated forrvm
, and any other part of the program could allocate that memory.It just so happens that a call to
opendir
cause some memory on the heap to be modified, it doesn't directly/on purpose modify the string passed to it, especially since the argument is of typeconst char*
.EDIT: As Keith mentioned in the comments, when using C (not C++) it can be considered bad to cast the result of
malloc
. This question has discussion on the topic.