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;
This is your problem:
rvm_tis 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
opendircause 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.