473,503 Members | 1,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with dynamic memory allocation

hi group:

i've been struggling with this simple problem with dismay

i need all the file names in a directory
since the number of files in a directory is unknown, a friend here in
the group hinted me to use dynamic memory allocation: namely functions
like malloc etc

in the spirit of code re-use
i tried to find similar codes in the program "tree"
and found two wrapper functions xmalloc, xrealloc
without knowing why, i assume these wrappers are easier and safer to
use than the originals
so i wrote the following function read_image_files(), using those two
wrappers
i assume there are only 50 files in a directory,so
#define MAX_FILE_NUM 50

but when there are more than 50, my program eats up the CPU
and i don't know why

especially:
char **imagefiles = (char **)xmalloc(sizeof(char *) * MAX_FILE_NUM);
char **imagefiles = (char **)xmalloc(sizeof(char **) * MAX_FILE_NUM);
i have no idea which one to use and what the difference is

char ** read_image_files (char *dir_name)
{

char **imagefiles = (char **)xmalloc(sizeof(char *) *
MAX_FILE_NUM);

DIR *d;
struct dirent *ent;

int count = 0;

/*navigate the directory*/
while ((ent = (struct dirent *) readdir (d)))
{

count++;

/* if there's more files than predicted, add more*/
if(count MAX_FILE_NUM)
{

imagefiles = (char
**)xrealloc(imagefiles,sizeof(char *) * (sizeof(imagefiles)+ 1));

}
imagefiles[count-1] = ent->d_name;

}
return imagefiles;
}
void *xrealloc (void *ptr, size_t size)
{
register void *value = realloc (ptr,size);
if (value == 0) {
fprintf(stderr,"tree: virtual memory exhausted.\n");
exit(1);
}
return value;
}

void *xmalloc (size_t size)
{
register void *value = malloc (size);
if (value == 0) {
fprintf(stderr,"tree: virtual memory exhausted.\n");
exit(1);
}
return value;
}

Oct 25 '07 #1
1 1650
David d'Angers wrote:
....
i assume there are only 50 files in a directory,so
#define MAX_FILE_NUM 50

but when there are more than 50, my program eats up the CPU
and i don't know why

You want space for MAX_FILE_NUM pointers to char, so this is the right
call, except that
a) the cast is unnecessary (you don't need to cast void *)
and could mask problems

b) you can simplify the decision by using the clc approved form :-
char **imagefiles = xmalloc(sizeof *imagefiles * MAX_FILE_NUM);
>
char ** read_image_files (char *dir_name)
{

char **imagefiles = (char **)xmalloc(sizeof(char *) *
MAX_FILE_NUM);
You want space for MAX_FILE_NUM pointers to char, so this is the right
call, except that
a) the cast is unnecessary (you don't need to cast void *)
and could mask problems

b) you can simplify the decision by using the clc approved form :-
char **imagefiles = xmalloc(sizeof *imagefiles * MAX_FILE_NUM);
DIR *d;
struct dirent *ent;

int count = 0;

/*navigate the directory*/
while ((ent = (struct dirent *) readdir (d)))
{
count++;
/* if there's more files than predicted, add more*/
if(count MAX_FILE_NUM)
{
imagefiles = (char
**)xrealloc(imagefiles,sizeof(char *) * (sizeof(imagefiles)+ 1));
sizeof(imagefiles) is sizeof(char **) - probably 4 or 8. Not helpful.
You've just shrunk your allocated space and you probably start storing
data in all sorts of unsuitable places...

Why not use
char **imagefiles = xrealloc(sizeof *imagefiles * count);
instead?

[When you've got the basics working you could look at an approach
which didn't realloc on each file after 50, for example by doubling
the size of the allocated space on overflow]
>
}
imagefiles[count-1] = ent->d_name;
I don't much like the [count-1] here, it may be more "elegant" to rework
where you increment the count...

More importantly (though possibly off-topic in clc) the manual tells me
that
"The data returned by readdir() may be overwritten by subsequent calls
to readdir() for the same directory stream."

So keeping a pointer to the name returned in the structure is unlikely
to be valid...

You need to create a copy of the string and store its address in
"imagefiles".

As you're clearly on a unix-like systems, you could do this with strdup():-
imagefiles[count-1] = strdup(ent->d_name);

}
return imagefiles;
}
The xmalloc and xrealloc wrappers take a fairly blunt approach to error
handling. It may be appropriate for this particular application, but
don't assume they would be universally applicable.
Oct 25 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2951
by: luigi | last post by:
Hi, I am trying to speed up the perfomance of stl vector by allocating/deallocating blocks of memory manually. one version of the code crashes when I try to free the memory. The other version...
9
4949
by: Tom | last post by:
What I mean is why can I only allocate const size stuff on the stack in C++? If I want to allocate a variable amount I need to use the OS API (Win32 in my case). Thanks, Tom.
6
8183
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory...
6
2379
by: Sandeep Chikkerur | last post by:
Hi, If the entire heap memory for dynamic allocation is not available, does the compiler always return NULL ? eg: char *s; s = (char *)malloc(...);
13
4687
by: xian_hong2046 | last post by:
Hello, I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time. An example from Thinking in C++ is to dynamically...
11
3026
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
24
19035
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array...
3
2946
by: ranjeetasharma81 | last post by:
Hi all, I have a big C-cod, in which there are lots of dynamic memory allocation used. I want to replace dynamic memroy allocation by static arrays. The following are the problems that i am...
14
3812
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
10
4380
by: swornavidhya.mahadevan | last post by:
Which allocation (Static / Dynamic) is suitable for the situation when we are trying to allocate for a overloaded memory when the memory is full and no space to allocate. What will happen if both...
0
7086
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7460
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1512
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
380
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.