malloc vs 'no-malloc' - help
Author |
Message |
GHouc #1 / 17
|
malloc vs 'no-malloc' - help
Quote:
> I have a question to all the C Gurus out there. (maybe the answer is > obvious) > What is the difference between using malloc and not using malloc. > I have a struct which I use only once in the program. There are two > ways I can think of which can be used in order to 'access' the struct. > First, I can create a pointer to the struct, and then allocate memory for > it > in order to use it. > The other way is to create a variable of the type of the struct. > What are the pro and cons of each method? Which one is more efficient? Why? > Which one should I use? Any help would be greatly appreciated.
Rafal, I'd suggest from your example that it makes little difference which form you use; in fact, you are probably asking for more problems by using a pointer (in addition to more lines of code). That said, however, I usually take the long view toward code development: that is, this is what I want the code to do at this moment in time, but what will I ask it to do in the future? Or some variation that I 'snip' from this code? If I had simply declared the structure type, I would have created code which is less-extensible than that using pointers. I would be forced to use fixed sized arrays, rather than having the flexibility of dynamically-allocated pointers to dynamically-allocated structures. This is an argument for pointers, in my mind. Also, when passing structures to functions, sorting groups of structures, and/or otherwise manipulating them en masse, it makes good sense to use pointers. The bottom line, though for me, is whether a variation of the code is going to be used in the future, in another application, then the decision tends toward pointers. Yours, Geoff Houck systems hk
http://www.*-*-*.com/ ~hksys
|
Sat, 02 Sep 2000 03:00:00 GMT |
|
|
Rafal Gasiore #2 / 17
|
malloc vs 'no-malloc' - help
Hi All, I have a question to all the C Gurus out there. (maybe the answer is obvious) What is the difference between using malloc and not using malloc. I have a struct which I use only once in the program. There are two ways I can think of which can be used in order to 'access' the struct. First, I can create a pointer to the struct, and then allocate memory for it in order to use it. The other way is to create a variable of the type of the struct. What are the pro and cons of each method? Which one is more efficient? Why? Which one should I use? Any help would be greatly appreciated. Below is an example to illustrate what I'm trying to say: btw, fatal_error() exits the program. First method: (malloc) #include <bla.h> ... typedef struct some_struct { int integer1; int integer2; char some_string[140]; Quote: } SS;
... main() { SS* Record; ... if ((Record = (SS*) malloc(sizeof(SS))) == 0) { fatal_error("Can not allocate memory!"); } ... Record->integer1 = some_function(x, y, z); ... free(Record); ... Quote: }
Method two (no malloc): #include <bla.h> ... struct some_struct { int integer1; int integer2; char some_string[140]; Quote: } SS;
... main() { SS Record; ... Record.integer1 = some_function(x, y, z); ... Quote: }
Regards - Raf --- DISCLAIMER: All opinions expressed above are entirely my own. Rafal Gasiorek
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Jack Klei #3 / 17
|
malloc vs 'no-malloc' - help
Quote: > Hi All, > I have a question to all the C Gurus out there. (maybe the answer is > obvious) > What is the difference between using malloc and not using malloc. > I have a struct which I use only once in the program. There are two > ways I can think of which can be used in order to 'access' the struct. > First, I can create a pointer to the struct, and then allocate memory for > it > in order to use it. > The other way is to create a variable of the type of the struct. > What are the pro and cons of each method? Which one is more efficient? Why? > Which one should I use? Any help would be greatly appreciated. > Below is an example to illustrate what I'm trying to say: > btw, fatal_error() exits the program.
[example snipped] <Jack> There is no hard and fast answer. If the structure is very small and there is only one (or a few, or a small array) of them, most programmers will merely declare it (them). There is potentially a small performance advantage to doing it this way, because the compiler can generate code to directly address the members of the structure, as opposed to having to access the pointer to then access elements in the structure, but that could also be optimized away. If there are a large number of large structures, or the exact number need can't be determined until run time, most programmers would dynamically allocate them. On many platforms, variables can wind up in one of three memory areas (this is a common method of implementing C but by no means required by the language standard). These can be referred to as the static data area (global and static variables), the stack (local variables defined in functions without "static"), and the heap (initially unused memory which is available with *alloc functions). Under some operating systems, programs are limited to a fixed amount of stack space, but are allowed to access larger amounts of heap space, which is another reason why large arrays are often dynamically allocated at run time even when the size of the array is a compile time constant. Some of this is system specific, and some of this is programming style, so others may express differing opinions. </Jack>
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Ben Caradoc-Davi #4 / 17
|
malloc vs 'no-malloc' - help
[snip] : I have a struct which I use only once in the program. There are two : ways I can think of which can be used in order to 'access' the struct. : First, I can create a pointer to the struct, and then allocate memory for : it : in order to use it. : The other way is to create a variable of the type of the struct. : What are the pro and cons of each method? Which one is more efficient? Why? : Which one should I use? Any help would be greatly appreciated. Short answer: Use a struct variable, as it is more efficient and simpler to code and read. However, this means that you can't return a reference to the struct out of the function ... once the function returns the struct ceases to exist. Long answer: This is an implementation issue. Generally, C compilers produce machine code which uses two separate areas of memory: the stack and the heap. Each time a function is called, space for the function's automatic (local) variables is made on the stack, and when the function returns, the stack is popped and that space is liable to be overwritten by further function calls. If you need more space, you can get it from malloc (and friends), which allocate space on the heap. This is slower because it relies on a function call, and introduces the possibility of memory leaks because memory allocated on the heap must be explicitly freed. However, allocating objects on the heap allows more freedom, such as arrays whose size is not known at compile time, and returning pointers to objects on the heap from functions. With freedom comes responsibility. :-) The main contentious issue is that (in my humble experience) the stack is much more limited in size, but this is entirely implementation dependent. You might have a 1 Meg stack limit, and 128 Megs of physical RAM, 128 Megs of swap space (256 Megs of virtual memory) ... so malloc(250L*1024*1024); /* allocating on the heap */ might succeed (fits in the heap), but char s[1024L*1024+1]; /* allocating on the stack */ might fail with a stack overflow (exceeds stack size). Many C programmers who cut their teeth on the PC have been traumatised by the 64 kB stack limitation common in some early compilers, and seem very reluctant to use allocation on the stack, despite its efficiency. However, we here at comp.lang.c often get scientific programmers who try to allocate large arrays on the stack and then get stack overflows. This can sometimes be fixed with ulimit under Un*x, but that is beyond the scope of this group. So, it cuts both ways. -- Ben Caradoc-Davies Be sure to include a "cookie-for-procmail" in any email sent to me.
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Stephan Wilm #5 / 17
|
malloc vs 'no-malloc' - help
Quote:
> Hi All, > I have a question to all the C Gurus out there. (maybe the answer is > obvious) > What is the difference between using malloc and not using malloc.
Hi Rafal Gasiorek, If you use "malloc()" you dynamically allocate an amount of memory at runtime, if you don't you don't. Quote: > I have a struct which I use only once in the program. There are two > ways I can think of which can be used in order to 'access' the struct. > First, I can create a pointer to the struct, and then allocate memory > for it in order to use it. > The other way is to create a variable of the type of the struct. > What are the pro and cons of each method? Which one is more efficient? Why? > Which one should I use? Any help would be greatly appreciated.
In simple case like this, it is almost irrelevant. Typically you would use "malloc()" to allocate memory that you want to free again or when you do *not* know at compile time how much memory you'll need at runtime. This describes some of the two main features of dynamic memory allocation: 1) You can caclculate the amount to allocate at runtime 2) You can free the memory again at runtime 3) You get a return value telling you wether the memory is available or not. This is a *very* important difference to using local variables, where you never know, when the stack bursts. 4) You can make the pointer to the memory a local variable, thereby elegantly avoiding the use of global variables whenever you fear that the stack might be too small. [SNIP of source code] In a case like this, where it's only a simply structure, I'd declare it as a local variable. It's simpler and more straight forward. Stephan (initiator of the campaign against grumpiness in c.l.c)
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Kaz Kylhe #6 / 17
|
malloc vs 'no-malloc' - help
Quote:
>Hi All, >I have a question to all the C Gurus out there. (maybe the answer is >obvious) >What is the difference between using malloc and not using malloc. >I have a struct which I use only once in the program. There are two >ways I can think of which can be used in order to 'access' the struct. >First, I can create a pointer to the struct, and then allocate memory for >it >in order to use it. >The other way is to create a variable of the type of the struct. >What are the pro and cons of each method? Which one is more efficient? Why? >Which one should I use? Any help would be greatly appreciated.
In general, it is more efficient to avoid using malloc and simply declare the objects in auto or static storage. It also avoids memory fragmentation and leaks. It's not that it's less efficient to access the dynamic objects, but rather that there is overhead associated with the storage allocator functions. In some cases, the compiler can optimize access to automatic variables better than to dynamic variables, because you aren't going through a pointer. For example, if you declare two identical structures in the same statement block, the compiler can see that if you access one of them, it has no effect on the value of the other. If you have pointers to two structures, the compiler does not necessarily know that the structures don't overlap. This is a smaller advantage, since you will most likely end up using libraries that take pointers to the structure as arguments rather than doing all the work in the same scope where the object is declared. If you just need one instance of something in your entire program, and its size is known at compile time, it is usually a good idea to allocate it statically or in automatic storage---as long as you don't write your code so that it does not later allow multiple instantiation of that thing, should the need arise! The best libraries will operate on data structures that are located anywhere the programmer wishes. Also, if your program needs to work with a variable quantity of some data item, with a small upper limit on the number of these items, you can allocate them from a fixed array. Dynamic allocation is best reserved for situations when you cannot predict how much data you will need to hold in memory, and the software's requirements don't allow termination as an adequate response to a large data set. Quote: >Below is an example to illustrate what I'm trying to say: >btw, fatal_error() exits the program. >First method: (malloc) >#include <bla.h> >... >typedef struct some_struct { > int integer1; > int integer2; > char some_string[140]; >} SS; >... >main() { > SS* Record; > ... > if ((Record = (SS*) malloc(sizeof(SS))) == 0) { > fatal_error("Can not allocate memory!"); > } > ... > Record->integer1 = some_function(x, y, z); > ... > free(Record); > ... >} >Method two (no malloc): >#include <bla.h> >... >struct some_struct { > int integer1; > int integer2; > char some_string[140]; >} SS; >... >main() { > SS Record; > ... > Record.integer1 = some_function(x, y, z); > ... >}
This is just as good. The one disadvantage is that if some_struct is very large, there is no way to detect failure to allocate it. With malloc, you can always test for a null pointer, but overflowed stack storage tends to just crash your program. I wouldn't worry about this unless the code needed to be ported to some very tiny embedded system. Under MS-DOS, your stack is limited to 64K.
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Exil Q Tr #7 / 17
|
malloc vs 'no-malloc' - help
Quote: >What is the difference between using malloc and not using malloc.
malloc() is extremely useful in solving certain kinds of problems. Your example is not one of them. So in general, not using malloc() will offer a simpler solution. [Semi-Exception: In something like a job-interview situation, you may want to demonstrate that you know *how* to use malloc(). This may be commendable, but recognize also that malloc() can be expensive; if it's not needed, make sure the interviewer knows that you understand that it's not needed, and wouldn't use it in production code unnecessarily.] David G
|
Sun, 03 Sep 2000 03:00:00 GMT |
|
|
Ben Caradoc-Davi #8 / 17
|
malloc vs 'no-malloc' - help
: Do you know of a good reference work (Web page or otherwise) that describes : possible reasons for an application stack to get corrupted while a compiled : program executes? : I inherited a program that, for some reason, refuses to initialize for-loop : counters beyond some point. I suspect the stack is hosed at this point, but : don't know how that could be... This could be an implementation specific problem. The C standard does not require a stack. What compiler are you using? Have you contacted the vendor? Read troubleshooting info in the manual? Asked in a compiler-specific newsgroup? Can you compile with debugging and examine the state of the program when it crashed? If you find the suspect code, post some source (a useful-sized snippet) and we can take a gander. -- Ben Caradoc-Davies Be sure to include a "cookie-for-procmail" in any email sent to me.
|
Mon, 04 Sep 2000 03:00:00 GMT |
|
|
Rafal Gasiore #9 / 17
|
malloc vs 'no-malloc' - help
I would like to thank everyone who has replied to my question, either through email or this news group, I really appreciate it. The following is a brief summary of what people have said (in my own words). If I have misinterpreted anything, please let me know. malloc | 'no-malloc' = = = = | = = = = - uses heap | - uses stack - heap size is virtually unlimited | - stack has limited size | (except under UN*X - use ulimit) - use when application will be | extended at a later stage | | - use when structure is small - allows for better manipulation | - can't return references to the struct due to the use of pointers | out of a function - the struct ceases | to exist | - may be quicker as the compiler may | optimise the code more efficiently | - may be quicker as there are no | overheads for function calls - will 'tell' when memory can | - the program will just crash when the not be allocated | stack is out of memory - portable to all systems | - could cause problems under systems | which have a small stack space | ie MS-DOS (64k) Regards - Raf --- DISCLAIMER: All opinions expressed above are entirely my own. Rafal Gasiorek
|
Mon, 04 Sep 2000 03:00:00 GMT |
|
|
Will Ro #10 / 17
|
malloc vs 'no-malloc' - help
: Ben: (and others) : Do you know of a good reference work (Web page or otherwise) that describes : possible reasons for an application stack to get corrupted while a compiled : program executes? Debugging C, R Ward, QUE. : I inherited a program that, for some reason, refuses to initialize for-loop : counters beyond some point. I suspect the stack is hosed at this point, but : don't know how that could be... You are probably writing over the stack with a wrongly-initialised pointer to a local variable. But a lot depends on the implementation - the way I usually write over the stack is to run the heap into it, which you can't generally do with modern OSes. Will
|
Mon, 04 Sep 2000 03:00:00 GMT |
|
|
Stephan Wilm #11 / 17
|
malloc vs 'no-malloc' - help
Quote:
> The following is a brief summary of what people have said (in my own > words). > If I have misinterpreted anything, please let me know.
[most of GOOD summary snipped] I have picked out two of your comments in favour of "malloc()" for a small additional remark: Quote: > stack has limited size (except under UN*X - use ulimit) > the program will just crash when the stack is out of memory > could cause problems under systems
From practice with lots of different compilers I have learned that these are in fact the most serious arguments against using *large* local variables. You might have one very good compiler that handles the stack requirements really very good , and the next ANSI-C compiler that you use won't. There seem to be (at the moment) more compilers with not-so-good stack handling. They do *not* automatically adapt the stack size to the requirement and have some mean upper limit. Using stack space sparingly is a good technique for writing robust code. Stephan (initiator of the campaign against grumpiness in c.l.c)
|
Mon, 04 Sep 2000 03:00:00 GMT |
|
|
Page 1 of 2
|
[ 17 post ] |
|
Go to page:
[1]
[2] |
|