tags:

views:

111

answers:

4

Hi All,

I have an issue regarding freeing memory as under:

            string points; // some points sequences

    char* charPoints = (char*)malloc((points.length() +1) * sizeof(char));

            //do something

    free(charPoints);

Even then after freeing memory is leaked when checked with instruments

+2  A: 

The only problem I see is when malloc returns NULL because it can't allocate enough contiguous memory. Are you sure that the memory leak is due to the malloc/free?

vulkanino
@vulkanino i have checked using instruments. it showed the memory leak at that point.
iSight
At which point? After free of the char variable? The leak may be shown due to other elements allocated and not freed. Would help if you provide more information.
Praveen S
A: 

Your instruments for leak detection are bad.

Alexey Malistov
@Alexey You need to be more carry out with memory leaks problem...
iSight
+2  A: 

The pointer you pass to free must be the same one which returned by malloc. If you pass a different pointer it will result in a undefined behavior. Take a copy of the pointer before you do the operation such as incrementing the charPoints and then pass this original pointer to free function to properly release memory.

Naveen
@Naveen Thanks for this suggestion...
iSight
@naveen thanks again it did really work out..
iSight
To garantee this you can make it const: `char* const charPoints = (char*)malloc((points.length() +1) * sizeof(char)); `
Charles Beattie
@Charles if this is the case, even if i increment the pointer will it work.
iSight
No this just prevents you from incrementing the pointer.Take a copy of the pointer and increment that.
Charles Beattie
A: 

After freeing the memory update with NULL value shown bellow

free(charPoints); charPoints ="NULL"

badusha