473,569 Members | 2,844 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_file s(), 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(size of(char *) * MAX_FILE_NUM);
char **imagefiles = (char **)xmalloc(size of(char **) * MAX_FILE_NUM);
i have no idea which one to use and what the difference is

char ** read_image_file s (char *dir_name)
{

char **imagefiles = (char **)xmalloc(size of(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(ima gefiles,sizeof( char *) * (sizeof(imagefi les)+ 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 1660
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_file s (char *dir_name)
{

char **imagefiles = (char **)xmalloc(size of(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(ima gefiles,sizeof( char *) * (sizeof(imagefi les)+ 1));
sizeof(imagefil es) 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
2962
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 seem to work. I would appreciate someone to comment on this. Version 1 (crashes on deallocating) #include <iostream>
9
4954
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
8186
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 allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new...
6
2389
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
4694
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 create an array (using "new") since one doesn't know it size when writing the program. However, it looks to me that the size information must come...
11
3030
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
19045
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 is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
3
2982
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 facing: 1- From structure and dynamic memory allocation point of view, the code is very complicated. The code has various “nested structures”...
14
3815
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 this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
10
4397
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 the allocation is impossible. Sworna vidhya
0
7695
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7922
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8119
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7668
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6281
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5218
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
936
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.