Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

NewbieA

How do i free up memory after malloc? Thanks

This topic is 5645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If i write a program like this, how could i free up the memory that i have malloc ?

unsigned short get_mem(unsigned short *string, size_t len)
{  string = (unsigned short *)malloc(sizeof(unsigned short)*len);
   return string;
}

main()
{ unsigned short *text;

  text = get_mem(text, 10);

  /* then if i try to use free(text); here or in another function, then it will get me a errormessge... */
  /* messges like "DAMAGE: after a Normal block..." */


  return 0;
}

What should i do? or do i need to free() anything at all? Thanks very much for any help

Share this post


Link to post
Share on other sites
Advertisement
Looks fine to me (well, if you had the free()) except two things :
- the function should return unsigned short * (probably a typo)
- doing get_mem( text, 10 ); won''t change text

For that second one :


/* C (note: need to dereference on the malloc line) and return */
unsigned short * get_mem( unsigned short ** string, size_t len );
get_mem( &text, 10 );

// C++

unsigned short * get_mem( unsigned short *& string, size_t len );
get_mem( text, 10 );

Share this post


Link to post
Share on other sites
I''d prefer the first version (C), the second version is simply too bastardized syntax for me (*&, good Lord!)

Share this post


Link to post
Share on other sites
their seeems to be no point of your function...
why not call malloc right away?

your first argument to the get_mem function has no point either. you could as well do (prefered way of doing it):
unsigned short *get_mem(size_t len)
{
return (unsigned short *) malloc(sizeof(unsigned short)*len);
}

unsigned short *text = get_mem(10);


if you want your function to assign your pointer you would do:
void get_mem(unsigned short **p, size_t len)
{
*p = (unsigned short *) malloc(sizeof(unsigned short)*len);
}

unsigned short *text;
get_mem(&text, 10);


and as always, you should have a mathing free with each malloc.
just do:
free(text);
to free your allocated memory.

[edited by - doho on June 19, 2003 1:39:48 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by NewbieA
if i try to use free(text); here or in another function, then it will get me a errormessge

That''s most likely because you are writing outside the bounds of the allocated memory. When asking questions about code, you should post the *actual* code you are having a problem with.

Share this post


Link to post
Share on other sites
Well, here is my code...
Problem: how could i free the allocated memory? I try free(), but get error messages...
(um...maybe i should just call malloc right away... @_@
(by the way, you guys would properly find my code very trival, but i''m just a newbie,...you know.)



// --dealing WORD code-set here-- //

#include "stdafx.h"

#define MAXnext 50
#define textfile "text.txt"
#define patternfile "pattern.txt"

size_t chkfile(char *fname);
unsigned short *readfile(unsigned short *string, char *fname, size_t len);
unsigned short *get_mem(unsigned short *string, size_t len);

int main(int argc, char * argv[])
{
unsigned short *text, *pattern; /* text, pattern storage */

unsigned int textlen=0, patternlen=0, found;


/* check file existence */
textlen=chkfile(textfile);
patternlen=chkfile(patternfile);
if(!textlen || !patternlen)
{ printf("\nText/pattern file not found.");
exit(1);
}

/* alloc memory for both string */
text=get_mem(text, textlen);
pattern=get_mem(pattern, patternlen);
if(text==NULL || pattern==NULL)
{ printf("\nMemory cannot be allocated.");
exit(1);
}

/* readin text and search pattern */
text=readfile(text, textfile, textlen);
pattern=readfile(pattern, patternfile, patternlen);


printf("\nInput string:\n%s", text);
printf("\nSearch pattern:\n%s", pattern);


return 0;
}


/* chkfile, check for file existence. *
* input: fname, string of the filename. *
* output: i (size_t), size in word. *
* NULL, when file NOT exist. *
*/

size_t chkfile(char *fname)
{ FILE *fp;
unsigned int i=0;

fp=fopen(fname, "r");

if(fp==NULL)
return NULL;

while(fgetc(fp)!=EOF)
i+=1;

fclose(fp);

return i/2;
}

/* readfile, read in text string from file. *
* input: *string, pointer for storing string. *
* *fname, filename to be read from. *
* output: *string, return string pointer. *
*/

unsigned short *readfile(unsigned short *string,char *fname, size_t len)
{ FILE *fp;

fp=fopen(fname, "r");
if(fp==NULL)
return NULL;

// fread(string, len, 1, fp);


fscanf(fp, "%s", string);

fclose(fp);

return string;
}

/* get_mem, alloc required memory for string storage. *
* Also reset the rquested memory to NULL. *
*/

unsigned short *get_mem(unsigned short *string, size_t len)
{
string=(unsigned short *)malloc(sizeof(unsigned short)*len);
memset(string, NULL, len);

return string;
}




Once again, thanks everyone!

Share this post


Link to post
Share on other sites
Oh, i still get the same error messgae after i change the code to use text=(unsigned short *)malloc(sizeof(unsigned short)*textlen) directly. Error message "After Normal Block...".

What did i do wrong?




Thanks again

Share this post


Link to post
Share on other sites
Have you thought of using calloc() to allocate your memory. It has easier organisation for allocating arrays.

I''ve also noticed that you are not checking to see if the memory was assigned successfully by checking if malloc() returns NULL. I can''t remember off-hand if trying to free unassigned memory will give you errors - even though I think it will.

Beginners and experts will find answers here.

Share this post


Link to post
Share on other sites
I rewrote your program a little bit, it is by no means perfect and more error checking should be added. Hope it can help you.


// includes

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// defines

#define TEXT_FILE "text.txt"
#define PATTERN_FILE "pattern.txt"

// prototypes

char *read_file(const char *file_name);

// main

int main(int argc, char * argv[])
{
char *text;
char *pattern;

// read in files

text = read_file(TEXT_FILE);
pattern = read_file(PATTERN_FILE);

// failed to read files?

if(!text || !pattern)
{
printf("error");
}

// free file buffers

if(text) free(text);
if(pattern) free(pattern);

return 0;
}

// read_file

char *read_file(const char *file_name)
{
FILE *f;
int size;
char *mem;

// open file

f = fopen(file_name, "r");
if(!f)
{
return NULL;
}

// determine size of file

fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);

// allocate memory for file

mem = (char *) malloc(size);

// read file into memory

fread(mem, size, 1, f);

// close file

fclose(f);

return mem;
}



[edited by - doho on June 19, 2003 1:43:03 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Mathematix
Have you thought of using calloc() to allocate your memory. It has easier organisation for allocating arrays.



calloc sets all the bits to 0, so it''s a little slower for no benefit in nearly all cases. Just follow the idiom

myPointer = malloc(sizeOfArray * sizeof *myPointer);

and all''s well.

Also, memset(string, NULL, len) has a few problems. First, NULL isn''t guaranteed to be all bits zero, you should use either an explicit 0 or, if you want to use the NUL character (note, one L) then you should use ''\0''. Second, the third paramter is the number of bytes in the array, not the number of elements. Use "len * sizeof *string" for the third parameter. Finally, I think that setting all bits of an unsigned short to 0 needn''t produce the result you expect, but I could be wrong on this point.

Don''t cast the return from malloc either. If the compiler complains, then you''re compiling it as C++ and should be using new instead. If you''re using C, it''s considered bad style to cast void pointers. It also masks the fact that you didn''t include stdlib.h, so you don''t have prototypes for malloc or free in scope, so the compiler believes that both malloc and free return int, which may be a source of problems.

Many congratulations on returning int from main, though Good to see that some people care about correctness

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!