Visual C++ :: How To Avoid Memory Fragments
Mar 4, 2015
I am developing a Visual C++ application. There is an object called CMyObject, as follows:
typedef CMap<UINT, UINT, void *, void*> CMyMap;
class CMyObject {
public:
CMyMap *m_pMyMap;
"Some other member variables"
}
Some instances of CMyObject contains a map, some not. Therefore, to save memory, I define a pointer m_pMyMap and create a new CMap object only if the instance contains a map.
When I test my app, with the increase of the CMyObject instance, the number of memory blocks allocated and deallocated is also increasing. There are a lot of fragments during this period. To prevent this, I try to override the new/delete operator for CMyObject and CMyMap. But still find many fragments. So I try to trace into the MFC source codes for CMap. I find CMap is just using an internal buffer to store the hash table(m_pHashTable), as follows:
m_pHashTable = new CAssoc* [nHashSize];
And for each hash entry, it uses:
P = (CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement];
To allocate the spaces.
I believe these two may be the reason of the memory fragments and want to eliminate them. However, is there a way to override the new/delete operator for codes such as:
new CAssoc* [nHashSize]
and
(CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement]
So that the spaces will be allocated from my own memory manager instead of from the default heap?
View 1 Replies
ADVERTISEMENT
Jul 12, 2013
I have a c program that I partially have working. The problem is basically writing a program that allows the user to input the amount of calories they plan to eat a meal and disperse the calories from top to bottom. My program produces the output in the example if I enter 1050 but the issue I noticed if the number of calories is just enough to cover the burgers I get negatives in the other variables.
For example, if I enter a total amount of calories of 1050, I can eat: Output: 2 burgers @ 770 calories (1050 - 770 = 280 calories remain) 1 bag of pretzles @ 170 calories (280 - 170 = 110 calories remain) 1 pear @ 80 calories (110 - 80 = 30 calories remain) 6 tsp. ketchup @ 30 calories If I input 1050 I get the above output but if I input a different integer such as 2000 this is my output 5 burgers @ 1925 calories 0 bag of pretzles @ 0 calories -1 apple @ -80 calories -35 tsp. ketchup @ -175 calories I can't give the full code since this assignment holds a lot of points and was up all night getting it work.
So I'll provide pseudocode
define all 4 variables burger 385, pretzel 170, pear 80, ketchup 5 print out text How many calories can you eat prompt user input
Divide user input into burger How many burgers can bet eaten subtract calories eaten from original user input
Divide calories left into pretzel How many bags can bet eaten subtract burger calories from pretzel calories
Divide calories left after preztel into pear How many pretzels can be eatn subtract pretzels calories from pear calories
Divide calories left over into ketchup how much ketchup can i use show on screen (int total)of burgers @ (int calorie total) calories show on screen (int total)bags of pretzels @ (int calorie total) calories show on screen (int total)pears @ (int calorie total) calories show on screen (int total)teaspoons of ketchup @ (int calorie total) calories
The problem I see is that subtracting the calories from the pear from the left over calories of the pretzel calories leads to a negative. If leftover calories minus 80(pear int) its less then 0 . The calculations from the pear onward to ketchup become incorrect resulting in negative output.
View 6 Replies
View Related
Dec 17, 2014
I've been making an RPG in C++ and I've used goto all throughout the program. After receiving an error and Googling how to fix it, I read that you shouldn't use goto. What can I use as a instead of goto, which isn't 'considered bad programming practice'?
View 9 Replies
View Related
Sep 4, 2014
ISSUE: How to avoid redundant code in c++ ?
Problem:Say I have a Base class called Car and it has 3 derived classes say Ford, Honda and Audi.
now the issue is all 3 derived classes have exactly same code but minor difference in calling member functions of their r respective engines( these engines have separate class) . example ford class calls code which is exactly same as other 2 classes but do call something like ford_engine-> start() ford_engine->clean() bla bla bla .
//ly honda calls honda_engine->start() honda_engine->clean();
//ly Audi calls audi_engine->start() audi->clean();
now here the issue is it has redundant code in all 3 places with minute difference. Hoow I can have code at one place most probably in Base class and all derive classes uses same code.
View 1 Replies
View Related
Apr 19, 2013
I have a class buffer, which holds a std::string as member, and a socket_receive function:
struct buffer {
string data;
buffer() {}
buffer(buffer& b) : data(b.data) {}
};
buffer socket_receive() {
buffer tmp;
tmp.data = "1234";
return tmp;
}
so when I write
buffer b = socket_receive();
there is a copy constructor, and the tmp variable is constructed and destructed, is there anyway to improve the performance?
I tried the new c++11 move(), but seems even worse, I must be doing wrong with move(), but I don't know how.
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct buffer {
string data;
[Code] .....
View 4 Replies
View Related
Jun 13, 2014
I have table called leavetable where in i have the fields eid, lfrom,lto, reason,status an employee will insert these fields in the leave form except status, status will be updated by admin but there is no unique field in the table so when the admin updates the status as cancel for an id emp001 so whereever this id is present in the table its getting updated to cancel even though it is approved previously.. How to avoid this duplication ?
SqlConnection con = new SqlConnection(Connectionstring);
con.Open();
string sql = "update leavetable set status = '"+status+"' where eid = '"+textBox1.Text+"' and noofdays = '"+textBox5.Text+"'";
[Code] .....
View 7 Replies
View Related
Oct 6, 2014
I am working on a parking lot scenario project using multidimensional arrays. The parking lot has 8 rows and 10 parking spaces in each row. Altogether there are suppose to be 30 cars parking in the lot and arrive in numerical order. I am suppose to generate a random number to represent the row and another to represent the space in the row.
The problem I have is that a few of the elements are being replaced. The project requires the car to check if the space is taken, if so it is to find another one. Here is what I have...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 8
#define COL 10
#define CARS 30
void parkTheCars(int result[ROW][COL]);
void displayArray (int result[ROW][COL]);
[Code] .....
View 1 Replies
View Related
Feb 7, 2014
Imagine these simple class:
Code:
class test {
public:
void write(string a) {
cout << a;
}
};
(these class wasn't tested... it's for these question)... Can avoid the class use the array operator('[]')?
View 7 Replies
View Related
Mar 28, 2014
How to avoid using Backspace character with push_back? I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:
string password2 = "";
cout << "PASSWORD: ";
ch = _getch();
while(ch != 13) //character 13 is enter {
password2.push_back(ch);
cout << '*';
ch = _getch();
}
And also, I try to use pop_back(); but it doesn't work either.
View 6 Replies
View Related
Jun 10, 2013
If the filename below is a directory, then the following loop goes to infinite.
std::ifstream in;
in.open(filename, std::ifstream::in);
if(in.fail()) return;
[Code].....
View 1 Replies
View Related
Feb 18, 2013
I have a JPEG in memory as a char* and a bytesize, if I save it to disk with a .jpg extension it's a perfect JPEG file. The thing is, I don't want to save it unless it's a minimum width/height. I got it into memory using a socket recv() call. What should I do ?
View 6 Replies
View Related
Apr 21, 2013
I use Visual C++ to write a native C++ application. How to know the maximum memory it will use during its execution?
View 5 Replies
View Related
Oct 26, 2013
I am using CByteArray as a buffer in Visual C++. I want to preallocate nSize memory for for CByteArray, so that later when I try to change the buffer, by calling SetSize, Add, Remove, etc., as long as all these operations are within nSize, CByteArray will not try to release the memory or reallocate the memory, so to eliminate the possibility of memory fragments in heap. Is that possible?
View 5 Replies
View Related
Apr 29, 2013
I know memory leak checking can sometimes have false positives. I turned on memory leak checking by adding
Code:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
Then calling
Code:
_CrtDumpMemoryLeaks();
in the App's constructor.
I traced the issue back to the constructor for a variable included in the app class. The variable is a class I declare in the project.
Code:
//Class declaration
#define NUM_MT_COLORS 16
struct clrTable {
COLORREF clrCode;
CString clrName;
[Code] ....
I get a memory leak error for every instance where a CString is set. I tried moving this to the MainFrame just to see if there was something with this being in the app, and saw the same memory leak errors.
I didn't include the functions in this class that manipulate this table. I didn't put it in the document because this is a multi-doc application and this table is universal to the program.
Is this an example of a false positive in the memory leak checker, or did I do something wrong?
View 7 Replies
View Related
Dec 20, 2012
when ending my app in the debugger, memory leaks will be shown like this:
Detected memory leaks!
Dumping objects ->
C:PROGRAM FILESVISUAL STUDIOMyProjectsleaktestleaktest.cpp(20) : {18}
normal block at 0x00780E80, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
How can I tell Visual c++ also to show me the memory leaks in a called dll?
View 14 Replies
View Related
Feb 27, 2014
I have a MFC app that has a CDHtmlDialog embedded in it. During run time i update the HTML content from the C++ code. There's a IMAGE tag in the content and the SRC for the tag is updated multiple times in a second to show different images.
Basically i go over a WHILE loop in the C++ and call a JavaScript function to update the "src" for the "img" tag.
The issue am seeing is that, after running this code for a while the application kinda hangs and the system takes up lot's of memory.
How to solve this, as all the code that's in the browser side of app is HTML & JavaScript. I looked through the C++ code plugged all memory leaks there.
View 1 Replies
View Related
Oct 31, 2013
When running my code in Visual Studio, there is a particular point in the code where my program is crashing. To debug this, I am adding a break point in Debug mode just before that point, and observing what happens as I step through the code. However, to get to this break point in the code takes about a minute of running the program. So I'm wondering if there is a tool in Visual Studio to reload the state of a program's memory from a previous run, so that I can immediately get to the break point without having to wait for a minute each time?
View 6 Replies
View Related
Mar 23, 2013
I am trying to use PCA, but it gives memory access violation error. Here is my sample code.
Code:
int main(...) {
.................
vector<float>input_array;
for(i=0;i<number_of_lines;i++) {
for(j=0;j<feature_vector_size;j++) {
input_array.push_back(read_feature[i][j]);
[code]....
View 1 Replies
View Related
Jan 21, 2013
I am getting "driver could not be loaded due to system error 8" error while connecting to SQL Server 2005 from VC++. Its also throwing out of memory error. Basically i am developing and ISAPI dll. I use the following code to connect to DB.
CDatabase DBConnection;
if(! DBConnection.IsOpen()) {
DBConnection.OpenEx("Driver={SQL Server};Server=10.120.110.30;Database=Test;Trusted_Connection=yes;", CDatabase:penReadOnly | CDatabase::noOdbcDialog);
[Code] .....
for CDatabaseConnection, i can see 2 different method to open the connection, OpenEx and Open. Whats the difference between OpenEx and Open?
View 7 Replies
View Related
Aug 6, 2013
I am using new operator, I don't recall what the allocator's name is. But what is the corresponding Exception (or derived classes) any try-catch block can cope with?
View 1 Replies
View Related
Mar 17, 2013
I have CAN Dll program for my application,which was separately used.Now I have included the Drivers program into my application Program and I am having this error System Access Violation Exception:Attempted to read or write protected memory.i am attaching the Dll code and Application code which is throwing this error.
[CODE]
The CAN Dll Code
int receive_data(unsigned char *data_output, int *MsgId, XLportHandle g_xlPortHandle){
XLstatusxlStatus, xlStatus_new;
XLevent xlEvent;
unsigned intmsgsrx=RECEIVE_EVENT_SIZE;
char *local_data ="11111111";
DWORD status;
xlStatus_new = xlSetNotification(g_xlPortHandle, &h, 1);
[code]...
My Application Code which is the receiver thread for accessing the messages got onto the CAN bus.
DWORD WINAPI Rcv_Msg(LPVOID param){
int*MsgId = new int;//msg id from CAN
intRcvVal;//0 = there is data in the queue; 1 = there is no data
unsigned int uMsgId;
*MsgId = 0;
unsigned char CanData[8];
[code]...
View 1 Replies
View Related
Mar 19, 2013
I had a quick question regarding a program I am trying to complete. I have the basics worked out, and everything seems to be done, but I am running into two issues.
1= The program keeps telling me "Run-Time Check Failure #3 - The variable 'order' is being used without being initialized."
and
2= When I reach my output screen I receive "Unhandled exception at 0x7751c41f in CISC 192 Project 3.exe: Microsoft C++ exception: std:Out_of_range at memory location 0x002eefb8.."
While the first one isn't necessarily a deal breaker the second one definitely is.
Code:
// Bookstore Project 3.cpp : Defines the entry point for the console application.
// Declarations
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <istream>
[Code] ....
View 2 Replies
View Related
May 11, 2013
I'm trying out the gmp library by building a simple pi calculation program (original, I know!). On a million digits of Pi I've debugged the program and seem to have about a megabyte too much of memory at the end of the program (I start with around 250k before any allocation begins and end at around 1200).
int main(int argc, char *argv[]) {
//set a//
int digitsofpi =1000000;
mpf_set_default_prec(log2(10) *digitsofpi );
mpf_t a;
mpf_init (a);
mpf_set_ui (a,1);
[code].....
View 2 Replies
View Related
Mar 8, 2013
I am looking for a way to run a process form memory, without having any executable. The application will be kept inside a resource and will be extracted during run time. It should be then started as a new process. I couldn't find a solution that works also on x64
View 5 Replies
View Related
Nov 6, 2014
We have a proprietary third-party library that we make calls into via an API. Through a series of API calls, this library manipulates specific sets of data. Prior to making these calls, there are some API calls that are necessary in order to initialize the library in preparation for a specific set of data. One of the calls tells the library to allocate some memory and then perform whatever initialization is required. This particular API call returns a pointer to char (char*) that is later used as an argument for a few other API calls. My question is... Is there a way, or maybe some kind of trick, to tell exactly how much memory was allocated? It doesn't matter whether or not the solution (if there is one) is C++ related, or some series of OS commands. FYI: We're running on Redhat Linux 6.2 and using GNU C++ 4.4.6.
View 5 Replies
View Related
Jan 31, 2015
So, it seems I have a bug in my code:
Code:
char *mem = malloc(9), *bottom = malloc(3), *in = "abc";
int position = 2, i;
mem = "onetwo";
printf("OLD mem = %s
", mem);
[Code]....
What I'm trying to do is insert "abc" in the 3rd position of "onetwo". Results would be "oneabctwo", but all I get is crashing.
View 9 Replies
View Related