0

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;
AusCBloke
  • 18,014
  • 6
  • 40
  • 44
CuriousCoder
  • 1,582
  • 5
  • 28
  • 55

1 Answers1

2

This is your problem:

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

rvm_t is defined as a pointer to a struct rvm_info, therefore you're passing an incorrect size to malloc. sizeof(rvm_t) equates to the size of a pointer (usually 4 or 8 bytes) and NOT the size of a struct rvm_info (which is well over 4 or 8 bytes). You want the size to be that of struct rvm_info, NOT a pointer. Change that call to:

rvmBlock = malloc( sizeof(*rvmBlock) );

Which just means:

rvmBlock = malloc( sizeof(struct rvm_info) );

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 for rvm, 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 type const 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.

Community
  • 1
  • 1
AusCBloke
  • 18,014
  • 6
  • 40
  • 44