home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.os.msdos.programmer
- Path: sparky!uunet!world!levin
- From: levin@world.std.com (Levin F Magruder)
- Subject: Questions about malloc and free and memory models
- Message-ID: <BtxLAx.E1z@world.std.com>
- Organization: The World Public Access UNIX, Brookline, MA
- Date: Wed, 2 Sep 1992 03:20:56 GMT
- Lines: 79
-
- I'm posting here because I think my problems have to do with
- dos, not c. Correct me if I'm wrong.
-
- The program below does nothing but store lines from a file in
- malloced memory and then attempt to free that memory. I was
- getting "exception 13" from QEMM, the manual said that often
- meant segment wraparound, which I don't really understand,
- but I guessed that using far pointers would make it less likely,
- and it seems to've worked. But now the compiler (Borland C++ 2.0)
- complains about suspicious pointer conversions.
-
- Can someone point me to an introductory article on pc segments?
- Is there a way to avoid dealing with this when using dos? Or do
- I just have a bug in my program?
-
- I also don't understand the numbers I get from coreleft. They
- show memory sucked up after the mallocing, as I'd expect, but
- none freed at all until the very last free, when it is all freed
- at once. I thought this was perhaps because malloc works with
- chunks of memory, but even when I do huge files I get the same
- pattern.
-
- ------
- #include <stdio.h>
- #include "lines.h"
- #include <alloc.h>
-
- main(int argc, char ** argv)
- {
- FILE *infile ;
- struct line linedesc ;
- struct line far *linedescp, far *nextlinep ;
- char buffer[MAXLINE+1] ;
-
- infile = fopen(argv[1], "rt") ;
- if(infile == NULL)
- {
- printf("Can't open %s for reading", argv[1]) ;
- exit(-1) ;
- }
- printf("before: %u\n", coreleft()) ;
- linedescp = &linedesc ;
- while(fgets(buffer, MAXLINE, infile))
- {
- linedescp->text = (char *) malloc(strlen(buffer)+1) ;
- strcpy(linedescp->text, buffer) ;
- linedescp->next = (struct line far *) malloc(sizeof(struct line)) ;
- linedescp = linedescp->next ;
- }
- linedescp->text = NULL ;
- linedescp->next = NULL ;
- printf("after: %u\n", coreleft()) ;
-
- /* now free it all */
-
- linedescp = &linedesc ;
- while(linedescp->text != NULL)
- {
- free(linedescp->text) ;
- nextlinep = linedescp->next ;
- free(linedescp) ;
- linedescp = nextlinep ;
- }
- printf("Before last free: %u\n", coreleft()) ;
- /* freed all but last element. free the linedesc, but nothing was
- malloced for text, so don't free -> text */
- free(linedescp) ;
- printf("After last free: %u\n", coreleft()) ;
- return ;
- }
- ---lines.h---
- struct line
- {
- char *text ;
- struct line far *next ;
- struct line far *prev ;
- } ;
-
- #define MAXLINE 200
-