473,729 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Debug memory allocation with STL

Hi,

I have some problems when debugging memory allocation (for both malloc
and new) in a program that uses standard lists and vectors. When I add
an element to the vector, the overloaded "delete" operator is called
somewhere in the STL library and it cannot find the allocated memory.
How can I avoid this problem ? Can I overload new and delete only in my
code and not in the STL?

You can see my problem by compiling the mem.cpp joined file:

g++ -g -Wall -lpthread -o mem mem.cpp

Then debug it by gdb

gdb mem

gdb> run

Examine the stack. It's curious that the problem happen at k = 64

int main ()
{
vector<A> va;

for (int k = 0; k < 10000; k ++)
va.push_back(A( ));

int* i = new int;
delete i;

return 0;

}

I think that the STL allocates 64 entries by default in the vector and
if that isn't enough, it frees and allocates memory for that task.
Unfortunately, this interfere with my memory debugger.

Thank you for your help,

Riadh.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#include <list>
#include <string>
#include <vector>
#include <map>

using std::vector;
using std::string;
using std::list;
using std::map;
using std::pair;

#define MMAX 1024

typedef struct {
void* address;
char* file;
int line;
char* function;
} MINFO;
void *xmalloc_(int, const char*, int);
void xfree_(void *, const char*, int);
#define xmalloc(size) xmalloc_(size, __FILE__,__LINE __)
#define xfree(ptr) xfree_(ptr, __FILE__,__LINE __)
#define xrealloc(ptr,ne wsize) xrealloc_(ptr, newsize, __FILE__,__LINE __)
#define header_new() header_new_(__F ILE__,__LINE__)
inline void * operator new(size_t size, const char *file, int line)
{
return xmalloc_(size, file, line);
}
inline void operator delete(void *ptr)
{
xfree_(ptr, NULL, 0);
}
#define new new(__FILE__, __LINE__)

// src

int mstart;
MINFO marray[2][MMAX];
pthread_rwlock_ t mlock;
void marray_add(void * ptr, const char* file, int line)
{
int i = 0;

while (i < MMAX) {
if (marray[mstart][i].address == 0)
break;
i++;
}

if (i == MMAX) {
printf("Malloc debugger: too many allocated pointers");
abort();
}

marray[mstart][i].address = ptr;
marray[mstart][i].file = strdup(file);
marray[mstart][i].line = line;
marray[mstart][i].function = 0;
}

void marray_delete(v oid* ptr, const char* file, int line)
{
int i = 0, j;

for (j = 0; j < 2; j++)
for (i = 0; i < MMAX; i++) {
if (marray[j][i].address == ptr)
goto add_adress_foun d;
}

/* adress was not found */
printf("Malloc debugger: free a wrong address");
abort();
return;
add_adress_foun d:

marray[j][i].address = 0;
free(marray[j][i].file);
marray[j][i].file = 0;
marray[j][i].line = 0;
marray[j][i].function = 0;
}

void marray_replace( void* ptr, void* newptr, char* file, int line)
{
int i = 0, j;

for (j = 0; j < 2; j++)
for (i = 0; i < MMAX; i++) {
if (marray[j][i].address == ptr)
goto replace_adress_ found;
}

/* adress was not found */
printf("Malloc debugger: realloc with a wrong address!");
abort();

replace_adress_ found:

free(marray[j][i].file);

marray[j][i].address = newptr;
marray[j][i].file = strdup(file);
marray[j][i].line = line;
marray[j][i].function = 0;
}

void *xmalloc_(int size, const char* file, int line)
{
void *ret;

assert(size > 0);

ret = malloc(size);

assert(ret);

pthread_rwlock_ wrlock(&mlock);

marray_add(ret, file, line);

pthread_rwlock_ unlock(&mlock);

return ret;
}

void xfree_(void *ptr, const char* file, int line)
{
assert(ptr);

pthread_rwlock_ wrlock(&mlock);

marray_delete(p tr, file, line);

pthread_rwlock_ unlock(&mlock);

free(ptr);

}

void *xrealloc_(void *ptr, int newsize, char* file, int line)
{
void *newptr;

assert(newsize > 0);

newptr = realloc(ptr, newsize);

assert(newptr);

pthread_rwlock_ wrlock(&mlock);

if (ptr == NULL) {
/* equivalent to malloc */
marray_add(newp tr, file, line);
} else {
marray_replace( ptr, newptr, file, line);
}
pthread_rwlock_ unlock(&mlock);

return newptr;
}

class A {
int abc;

public:
A();
};

A::A()
{
abc = 0;
}

int main ()
{
vector<A> va;

for (int k = 0; k < 10000; k ++)
va.push_back(A( ));

int* i = new int;
delete i;

return 0;

}

Jul 22 '05 #1
1 2343
On Tue, 27 Jan 2004 11:30:01 +0100, Riadh Elloumi <ri***@melix.ne t>
wrote:
Hi,

I have some problems when debugging memory allocation (for both malloc
and new) in a program that uses standard lists and vectors. When I add
an element to the vector, the overloaded "delete" operator is called
somewhere in the STL library and it cannot find the allocated memory.
How can I avoid this problem ? Can I overload new and delete only in my
code and not in the STL?


Not very easily. You can of course use a custom allocator for the STL,
but this effects all of your container declarations. Some libraries
(STLport and SGI for two) let you configure the implementation of
std::allocator, giving you the option of using malloc rather than
operator new. Consult your library allocator documentation to see
whether this is an option.

The easiest solution is probably to override the operator new used by
other code - just provide an overload of the normal global operator
new:

void* operator new(std::size_t size)
{
return xmalloc_(size, "library allocation", 0);
}

or similar. Now your operator delete override will correctly free that
memory too.

Part of your problem mostly comes from redefining new with a macro,
which is of course illegal (MFC makes the same mistake IIRC). It
prevents use of placement new, etc. It requires that you #include your
debug alloc header after anything that might use new (such as standard
library headers). You might be better off replacing "new" with
something like "MYNEW" (which won't interact with anything other your
own code).

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1549
by: liangrf | last post by:
My server app is transformed from environment of UNIX to Windows. Its ran on the Apache Windows Server. The code is compiled pass by MSVC6 and ran well. but it has more memory leak. when I am debugging the code with windbg, insertting mang break, and step by step running code, the app do not appare memory leak at all. I am confused. if the app run without debugging, then the memory would increse by watching task manager. I think...
6
8210
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
1
2074
by: spiff | last post by:
We are migrating from VC++ 6 to VC++ 2003. It is a plain, unmanaged application with both C and C++ source. When running the debug build, even outside the debugger, the memory allocation/deallocation performance appears to be orders of magnitude slower than in VC++ 6. The release build runs fine - no performance problems. We've rewritten some of the code to do fewer memory allocations/deallocations and that has helped those pieces. However,...
6
2278
by: Boni | last post by:
Dear all, I have following problem. I created a static libruary (mylib.lib). I compiled it with Multithreaded DLL runtime in release mode. Now I want to give out this library. But users who use it should be able to debug their programs (i.e. compile their programs in debug mode Multithreaded DLL DEBUG runtime ). But at link time following warning is shown and prog crashes. Do I have to
62
17824
by: ivan.leben | last post by:
How can I really delete a preloaded image from memory/disk cache? Let's say I preload an image by creating an Image object and setting its src attribute to desired URL: var img = new Image(); img.src = ; Then I use the image a few more times by adding it into an Array object:
66
3625
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
24
19085
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
1
7970
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
66
3689
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.