开发者

What's the best method to free memory?

I'm working on ANSI C.

I have a string object which created with array of char.. I think the object make a memory leak.. when I run my program about five minutes (maybe almost 10000 iteration) my used memory become bigger and bigger..

I tried to free my object used memory with free and delete function. but, delete isn't a valid function. in the other side, free looks like running well first. but I got free():invalid pointer..

How can I fix this? I can do it differently?


here's a little of my code..

char *ext;
ext = calloc(20, sizeof(char));
//do something with ext
fre开发者_Go百科e(ext);


In C, you allocated memory on the heap with malloc, and release is with free. So you are correct there. delete is used in C++, and then, only if the memory was allocated with the new operator.

If you are getting an invalid pointer error in your call to free, then there is likely a bug somewhere in the code, if you post it we could take a look at it.


Maybe you're writing past the end of the allocated memory. With

calloc(20, sizeof(char))

you allocate space for 20 characters (19 "regular" and a null terminator for strings).

Make very sure none of your strcat() try to write "regular" characters beyond str[18].


Without more code:

  1. An array in memory just prior to what ext points to overran its storage and corrupted a type of "header" that malloc() uses to track the size of the memory for subsequent calls to free() (think of ((size_t *)ext)[-1] holding the size from the malloc).
  2. You used a negative array index into ext[negative] that did the same corruption.
  3. ext somehow gets modified.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜