0

opendir在 C 中的函数有问题。这是代码:

声明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;
4

1 回答 1

2

这是你的问题:

rvm_t func()
{
   rvmBlock=(rvm_t)malloc(sizeof(rvm_t));
   return rvmBlock;
}

rvm_t被定义为指向 a 的指针struct rvm_info,因此您将不正确的大小传递给malloc. sizeof(rvm_t)等于指针的大小(通常是 4 或 8 个字节),而不是 a 的大小struct rvm_info(远远超过 4 或 8 个字节)。您希望大小为 ,而struct rvm_info不是指针。将该调用更改为:

rvmBlock = malloc( sizeof(*rvmBlock) );

这只是意味着:

rvmBlock = malloc( sizeof(struct rvm_info) );

否则,您将导致未定义的行为,因为您没有为整个struct rvm_info. 因此,您将该字符串存储在尚未分配给 的内存rvm部分中,并且程序的任何其他部分都可以分配该内存。

碰巧调用opendir导致堆上的一些内存被修改,它不会直接/故意修改传递给它的字符串,特别是因为参数是 type const char*

编辑:正如 Keith 在评论中提到的,当使用 C(不是C++)时,将malloc. 这个问题有关于该主题的讨论。

于 2011-12-07T03:31:24.423 回答