-
Memory leaks
What are some of the common problems that cause memory leaks?
would the char* in this cause one?
unsigned int loadtex(char*name) {
unsigned int img,texture;
ilGenImages(1, &img); ilBindImage(img); ilLoad(IL_JPG,name); texture = ilutGLBindMipmaps();
ilDeleteImages(1, &img);
return texture;
}
-
difficult to say without knowing how the memory that the char* points to was allocated.
Memory leaks occur when you use malloc() and forget to call free(), or similarly when you call new and forget to call delete.
for instance....
char* name="whatever.foo";
// your code here
// no memory leaks
name was statically allocated and memory taken care of by your compiler.
char* name=new char[ 13 ];
strcpy (name,"whatever.foo");
// call your func
// if you then do this.....
delete [] name;
// there is no memory leak
hth
-
Consider this:
Code:
char *DoSomething(const char *in)
{
char *out = malloc(strlen(in));
return out;
}
int main()
{
char *in = malloc(100); // ...hmm...one allocation...
char withThisString[] = "A day in the life of a programmer";
int x = 100;
while(x-- > 0)
{
in = DoSomething(withThisString);
//...now, 'out' gets malloc'd every loop!...
<< Memory Leak, 10 K of memory... <<
}
free(in); //<--Which is free'd here?
return 0;
<< Memory Leak ?? <<
}
-
Another "popular", (i.e. common), cause of, (diificult to find), memory leaks is using non thread safe stdlib calls in a multithreaded environment.