TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Frank Adam
from: George White
date: 1998-11-01 22:14:04
subject: malloc and the resulting

Hi Frank,

You wrote to Dominique Curtis:

FA>DC> I have a program that uses malloc to dynamically set aside memory for
FA>DC> storing categories.  The problem is, once I use the function, for

FA>DC> ...declarations
FA>DC> char *malloc();
FA>If this is one of your functions, don't do this. Call it
FA>my_malloc(); or even Malloc()
FA>Else if this is the stdlib.h malloc() then don't declare
FA>it, just include stdlib.h.  Also make sure you have all
FA>warnings switched on.

Seconded!

FA>DC> char *ps[30];
FA>DC> ...At start of program I initialize the array to be safe..
FA>DC> for(i = 0; i < 30; i++) //Initialize ps[] array for future dynamic
FA>You can do this much simpler by changing the declaration above to..
FA> char* ps[30] = {NULL};

Remember that that is an array of 30 pointers to char with the first
pointer initialised to NULL, all the other pointers have unknown values.

FA>DC> ...Also at start of program I free memory.... to experiment, I put it
FA>No need for it at the start, it's neat to do it before exiting though.

FA>DC> void get_categories()
FA>DC> {
FA>Couldn't see anything wrong in there, could be a bit tighter.

You missed a major problem in there... He is opening the file but in the
code posted it is never closed. That usually ends up causing all sorts
of odd errors (well it does here when I've got the logic wrong and
not closed files...) :-(

FA>DC> Now.. before I was freeing (ps), and had memory problems, so I altered
FA>DC> it to free ps[]... is that correct?
FA>No, you should free each element.
FA>i = 0;
FA>while(i < 30)
FA>{
FA>    if(ps)
FA>        free(ps[i++])
FA> }

For most compilers you don't need to check that the pointer is not NULL,
free() will anyway.

FA>DC> I don't know if it makes a diffence, but I am using the FILE *fp;
FA>DC> declaration in all file-operation files.
FA>DC> If needed, I can post the file functions that mess up. Thanks...
FA>That would be a good idea, i couldn't pick anything real wrong in the code
FA>you've posted, but maybe i've missed something so wait for
FA>the others..:-)

George

 * SLMR 2.1a * Computers eliminate spare time.

--- Maximus/2 3.01
* Origin: DoNoR/2,Woking UK (44-1483-717904) (2:440/4)
SEEN-BY: 396/1 632/0 371 633/260 267 270 371 634/397 635/506 728 639/252
SEEN-BY: 670/218
@PATH: 440/4 255/1 251/25 396/1 633/260 635/506 728 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.