Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

Only handles can be created of a managed class. Why?

$
0
0

Hi

I am beginner for Visual C++ and currently just learning the concepts of it.

I came to know that there are 2 classes: Managed class & Value class.

1) Value classes are like normal C++ class, whose objects can be created which will hold the data.

2) Managed classes are memory managed by garbage collector. But their objects can't be created only handles can be created. Why???

& Also please give me brief idea about that is instance? Is it just an object creation or something else?

Thanks


Can’t determine if Tab/Esc is pressed within case LVN_ENDLABELEDIT:

$
0
0

Hi all,

I am developing in Native C++ in a Win32 API environment using Visual Studio 2008. I need to determine if and when the Tab or Esc key is pressed when a listView is in Edit Mode within the LVN_ENDLABELEDIT notification.

I have tried sub-classing the system generated control without success. I can trap any other key but not the tab or escape keys. The excerpt from the sub-classed proc is:

switch(message)

{

case WM_CHAR:

           switch(wParam)

           {

           case 0x09: // Tab

                       // Program lines

                       break;

           case 0x1B: // Esc

                       // Program lines

                       break;

           }

}

I have also tried to use the method as found in the Code Project example and can’t get it to work, excerpt as follows:

tchar = (TCHAR)msg.wParam;

if(tchar == 0x1b) escKey=1;

I would prefer to use the Code Project’s suggestion, if I can get it to work. Or. perhaps there is a better way. Any suggestions, comments etc would be appreciated.

Regards,

Richard


plz help me .. /fatal error C1083: Cannot open include file

$
0
0

im using MicrosoftVisual Basic 2010 Express

c++

Errors >

1>------ Build started: Project: AppFirewall, Configuration: Debug Win32 ------
1>  Appfilter.cpp
1>Appfilter.cpp(11): fatal error C1083: Cannot open include file: 'Appfilter.h': No such file or directory
1>  Packetfilter.cpp
1>Packetfilter.cpp(11): fatal error C1083: Cannot open include file: 'Packetfilter.h': No such file or directory
1>  Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


Failure to add over 990 windows (STATIC and EDIT) to the original window (canvas)

$
0
0

I'm getting a failure when running in the release mode when I've added more than 990 windows (STATIC and EDIT) to the original window.  The application is looping through an XML file, creating a label for each XML tag, and creating a textbox for each value.

This works in Debug mode, but is really, really slow and it down-right doesn't work in Release mode resulting in the exception below, followed by the stack trace.

Unhandled exception at 0x7717e41b in LanceEditor.exe: 0xC0000005: Access violation writing location 0x00000003.

     ntdll.dll!7717e41b()     
     [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]    
>    msvcr100.dll!malloc(unsigned int size)  Line 89 + 0x3b bytes    C
     00000001()    
     1320c16b()    

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_VSCROLL, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
   fileTypeCombo = CreateWindow(L"COMBOBOX", L"TAP", WS_VISIBLE | WS_CHILDWINDOW | WS_BORDER | ES_CENTER | WS_VSCROLL | CBS_DROPDOWN | CBS_HASSTRINGS, 
	   4, 4, 200, 80, hWnd, fileTypeCombo_id, hInstance, NULL);
   browse = CreateWindow(L"BUTTON", L"Browse", WS_VISIBLE | WS_CHILDWINDOW | ES_CENTER, 204, 4, 100, 20, hWnd, browse_id, hInstance, NULL);
int itotalElements = 0;
while (S_OK == (hr = pReader->Read(&nodeType)))
    {
        switch (nodeType)
        {
        case XmlNodeType_Element:
		itotalElements++;
		HWND element_label = CreateWindow(L"STATIC", pwszLocalName, WS_VISIBLE | WS_CHILDWINDOW | ES_LEFT, 
					depth * DEPTH_MULTIPLIER, elementNumber * HEIGHT_MULTIPLIER + 20, 150, 20, ghWnd, NULL, hInst, NULL);
		break;
        case XmlNodeType_Text:{
		itotalElements++;
		HWND element_text = CreateWindowA("EDIT", pcLocalValue, WS_VISIBLE | WS_BORDER | WS_CHILDWINDOW | ES_LEFT, 
				depth * DEPTH_MULTIPLIER + 160, elementNumber * HEIGHT_MULTIPLIER + 20, 10 + (strlen(pcLocalValue)*cxChar), 20, ghWnd, NULL, hInst, NULL);

		break;
        }
	if(itotalElements>989)
		break;
    }

The code above is extracted from the entire application to give perspective.  I did multiple comparisons and when itotalElements is greater than 989 it fails, but if I use 988 it works.

Is there a way to configure the limit to the number of windows we can add to a canvas?

Is there any name available for VC++ compiler ?

$
0
0
Hi,
        As we have compiler names for VB & C# as vbc.exe and csc.exe, Do we have compiler name for VC++ also ? If so, what is the name ?

Thanks
Kiran 
Working as a software engineer

Neither cl.exe nor cdb.exe is found by Windows Search.

$
0
0

I am using VSE2013 and neither cl.exe nor cdb.exe is found by Windows Search.
In which directory would I find these files?


Worry is a misuse of imagination :)

Intermittent Access Violation in COleVariant destructor during the call to VariantClear() inside the destructor

$
0
0

Hi,

I'm facing an intermittent Access Violation in COleVariant destructor during the call to VariantClear() inside the destructor.

The first chance exception dump shows the access violation in oleaut32!VariantClear method.

I'm facing this issue on 64-bit Windows Server 2008 R2 Datacenter SP1. Also, this access violation is intermittent, i.e., with the same input data sometimes there is access violation and sometimes it runs fine. 

Is this a known issue on 64-bit Windows Server 2008 R2 Datacenter SP1 ? 

Tha sample code snippet is given below:

COleVariant var;

NUMPARSE np; //its members are properly populated with some values.

BYTE digits[SOMELEN];  //has some bytes as digits.

VarNumFromParseNum( &np, digits, VTBIT_R8, (LPVARIANT)var );

return; //access violation occurs here during the call toCOleVariant destructor.


Thanks,

Amit

Compiler ignores supression of warning C4200

$
0
0

As the title says, the Visual C++ 2010 compiler is not suppressing warning C4200 as directed. It's working correctly with other warnings however.

I've tried including the "C" prefix in both the command line and via #pragma and also tried reordering the list of suppressed warning IDs in both methods but to no avail.

This worked fine in VS2008.

-Matt


VS 2011: lib utility doesn't find mspdb110.dll problem

$
0
0

Hi, as the title says, if I try to use lib.exe, it exist with an error telling me that it cannot find mspdb110.dll. An easy fix is to copy in the same folder the file, that can be found in "VSPATH/Common7/IDE". But after I do this, the VS linker start throwing errors, so I need to undo the last modification.

What I am doing right now, is: copy missing dll, use lib.exe, delete missing dll, link.

But I don't like doing this every time, is there a more elegant fix... and more importantly, WHY is this happening?

Thanks

VS 2013 Quick Find scope changes spontaneously when using Control-F

$
0
0

I use Control-F to bring up the little Quick Find box at the upper-right of the Visual Studio editor window when I'm editing C/C++ files.

I guess it's by design, but the scope ("Current Document", "Selection", "Current Project", "Current Block") changes automatically, and while I can see it being helpful occasionally more often than not it changes the scope from what I want to something else.  Specifically, it quite often changes the scope from "Current Project" to "Selection".

 

 

Do you know if there is any way to configure VS to just stick with the scope I've selected, i.e., never automatically change it depending on the context of what I'm doing?

Thanks.

 

-Noel


Detailed how-to in my eBooks:  

Configure The Windows 7 "To Work" Options
Configure The Windows 8 "To Work" Options

Visual Studio 2013 resource compiler error RC2108 - fixed yet?

$
0
0

There was discussion here starting last Autumn under the heading:

Error "RC2108: expected numerical dialog constant" after project migration from VS2008 to VS2013

and a recent message suggests it is a bug which isn't fixed in update #2.

I've just started using Visual Studio 2013 in an environment where I don't have access to earlier versions (so the 'use 2010' suggested work-around doesn't help) although the project was imported from a VS 2010 project elsewhere.    It has been working for me - until I added a string to the string table using the visual interface, and now the resources don't compile - and in fact I can't even see them in the resource view - only as text.

(Several dialogues are producing the RC2108 error, and the lines identified are more to do with text controls than bitmaps.)

How do I continue work on the project?

David Webber

                                 

David Webber Author of Mozart music notation software http://www.mozart.co.uk

How to replace malloc/free/new/delete with own code

$
0
0

Hi experts,


Currently, in my project, I need to replace malloc/free/new/delete completely with my own implementation.

GNU C has hooks I could use to provide my own functions, is there some similar mechanism in Visual C++ 2005?

Is there any guideline about that?

 

Thanks & Regards,

Isomorphism

WM_RECOEVENT is not being sent

$
0
0
I'am developping a speech recognition application, all the code has been written correctly. However, SetNotifyWindowMessage would not send any message to the windows procedure
-WM_RECOEVENT never get called
#include "resource.h"
#include "grammar.h"
#include <windows.h>
#include <sphelper.h>
#include <string>
#define IDC_EDIT1                       1001
#define ID_START_RECOG					1002
#define WM_RECOEVENT	WM_USER+190


void CreateWnd(const char *title, int x = 200, int y = 100, int width = 640, int height = 490);
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void LaunchRecognition(HWND hWnd);
WCHAR *HandleEvent();
WCHAR *ExtractInput(CSpEvent event);


void Register(WNDCLASS &wc);

const char *szClassName = "win32App";

CComPtr<ISpRecognizer> cpEngine;
CComPtr<ISpRecoContext> cpRecoCtx;
CComPtr<ISpRecoGrammar> cpRecoGrammar;


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	WNDCLASS wc;
	Register(wc);
	CreateWnd("Speech Recognition");
	return 0;
}

void CreateWnd(const char *title, int x, int y, int width, int height) {
	
	HWND hWnd = CreateWindow(szClassName, title, WS_OVERLAPPEDWINDOW, x, y, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);
	if(hWnd == NULL) {
		MessageBox(NULL, "Unable to create window", "creating window", MB_ICONERROR);
	}

	ShowWindow(hWnd, SW_SHOWDEFAULT);
	UpdateWindow(hWnd);

	MSG msg;
	while(GetMessage(&msg, 0, 0, 0) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}

void Register(WNDCLASS &wc) {
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wc.hCursor = NULL;
	wc.hIcon = NULL;
	wc.hInstance = GetModuleHandle(NULL);
	wc.lpfnWndProc = WndProc;
	wc.lpszClassName = szClassName;
	wc.lpszMenuName = NULL;
	wc.style = 0;

	if(!RegisterClass(&wc)) {
		MessageBox(NULL, "Unable to register class", "registering class", MB_ICONERROR);
	}
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	static HWND hEdit;
	switch(uMsg) {
	case WM_CREATE:
		{
			hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_VISIBLE | WS_CHILD , 0, 0, 640, 400, hWnd, (HMENU)IDC_EDIT1, GetModuleHandle(NULL), NULL);
			HWND bButton = CreateWindowEx(0, "BUTTON", "Start Speech Recognition", WS_VISIBLE | WS_CHILD, 0, 410, 640, 30, hWnd, (HMENU)ID_START_RECOG, GetModuleHandle(NULL), NULL);
			//LaunchRecognition(hWnd);
		}
		break;
	case WM_RECOEVENT:
		{
			WCHAR *pwszText = HandleEvent();
			SetDlgItemText(hWnd, IDC_EDIT1, (char*)pwszText);
			//SetDlgItemText(hWnd, IDC_EDIT1, "\r\n");
		}
		break;
	case WM_COMMAND:
		switch(LOWORD(wParam))
		{
		case ID_START_RECOG:
			LaunchRecognition(hWnd);
			break;
		}
		break;
	case WM_CLOSE:
		cpRecoGrammar.Release();
		cpRecoCtx.Release();
		cpEngine.Release();
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default: 
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
	}
	return FALSE;
}

void LaunchRecognition(HWND hWnd)
{
	HRESULT hr = ::CoInitialize(NULL);
	if(FAILED(hr))
	{
		throw std::string("Unable to initialise COM objects");
	}
	hr = cpEngine.CoCreateInstance(CLSID_SpSharedRecognizer);
	if(FAILED(hr))
	{
		throw std::string("Unable to create recognition engine");
	}
	hr = cpEngine->CreateRecoContext(&cpRecoCtx);
	if(FAILED(hr))
	{
		throw std::string("Failed command recognition");
	}

	hr = cpRecoCtx->SetNotifyWindowMessage( hWnd, WM_RECOEVENT, 0, 0 );
	if(FAILED(hr))
	{
		throw std::string("Unable to select notification window");
	}

	hr = cpRecoCtx->SetInterest(SPFEI(SPEI_RECOGNITION), SPFEI(SPEI_RECOGNITION));
	if(FAILED(hr))
	{
		throw std::string("Failed to create interest");
	}

	hr = cpRecoCtx->CreateGrammar(0, &cpRecoGrammar);
	if(FAILED(hr))
	{
		throw std::string("Unable to create grammar");
	}

	hr = cpRecoGrammar->LoadCmdFromResource(
		NULL,
		MAKEINTRESOURCEW(IDR_SAPI0),
		L"SRGRAMMAR",
		MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL), SPLO_DYNAMIC);	
	if(FAILED(hr)) 
	{
		throw std::string("Error loading grammar");
	}

	hr = cpRecoGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE );
	if(FAILED(hr)) 
	{
		throw std::string("Error activating the rules");
	}
}

WCHAR *HandleEvent()
{
	CSpEvent event; 
	
	HRESULT hr = event.GetFrom(cpRecoCtx);

	if(hr == S_FALSE)
	{
		throw std::string("event failed");
	}
    // Loop processing events while there are any in the queue
    while (event.GetFrom(cpRecoCtx) == S_OK)
    {
        // Look at recognition event only
        switch (event.eEventId)
        {
            case SPEI_RECOGNITION:
				return ExtractInput(event);
        }
    }
	return (WCHAR *)"";
}

WCHAR *ExtractInput(CSpEvent event)
{
	// Declare local identifiers:
	HRESULT                   hr = S_OK;
	CComPtr<ISpRecoResult>    cpRecoResult;
	SPPHRASE                  *pPhrase;
	WCHAR                     *pwszText;

	cpRecoResult = event.RecoResult();
	// ... Obtain a recognition result object from the recognizer ...

	// Get the recognized phrase object.
	hr = cpRecoResult->GetPhrase(&pPhrase);

	if (SUCCEEDED (hr))
	{
	// Get the phrase's entire text string, including replacements.
		hr = cpRecoResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszText, NULL);
	}

	return pwszText;
}




here is the full code:

Visual C++ 2008 SP1 Redistributable Package

$
0
0

I'm running 64-bit Vista.  When trying to install Microsoft Visual C++ 2008 SP1 Redistributable Package I get the error:

"Error 1935.An error occured during installation of assembly 'Microsoft.VC90.ATL,version="9.0.30729.1",publicKey token="1fc8b3b9a1e18e3b",processorArchitecture="amd64",type="win32"'. Please refer to Help and Support for more information. HRESULT:0x80070424"

"80070424" is the came error code I get when I try to use Windows Update, which also hasn't been working.

Any help would be appriciated.  Thanks.

 

How to handle CTRL_CLOSE_EVENT?

$
0
0

static BOOL WINAPI console_ctrl_handler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: // Ctrl+C { break; //return TRUE; } case CTRL_BREAK_EVENT: // Ctrl+Break break; case CTRL_CLOSE_EVENT: // Closing the console window //event was caught //But I guess call exitProcess () break; //return TRUE; case CTRL_LOGOFF_EVENT: // User logs off. Passed only to services! break; case CTRL_SHUTDOWN_EVENT: // System is shutting down. Passed only to services! break; } // Return TRUE if handled this message, further handler functions won't be called. // Return FALSE to pass this message to further handlers until default handler calls ExitProcess(). return TRUE; }

My goal is IF user clicked close-button, App catch this event And Just warn and Keep going.

When I was debugging , close event successfully caught but process killed .

Yes, CTRL_C_EVENT was successfully igored and as I intended my program just keep going


How to solve it?

...



CMFCPropertyGridColorProperty and document colors / names

$
0
0

Hi

I am learning up on using CMFCPropertyGridColorProperty. But there is something I can't seem to find the answer to.

With the CMFCColoredButton it had a SetDocumentColors method and a SetColorName method. This meant I could have mu own group of colours with known colour names.

But using the CMFCPropertyGridColorProperty object it does not seem to support them. So I get two issues:

1. I can't show the say array of colours as elsehwre in my program.

2. The colours are shown in hexadecimal (where it would have been a known colour if using my list).

Thanks for clarification.

Andrew

CMFCColorButton - setting number of columns and other customizations

$
0
0

Hi

I am changing my program to use the new CMFCColorButton class. It is going OK but I have two issues.

Screenshot

Firstly, I did try to set the number of columns to 10. But it still restricts it to showing 5. The documentation does not state that the drop window is limited to the width of the colour. What is the rules here?

Secondly, is it possible to omit the first group of standard colours? In this context I would like the script colours. Or would that be bad practice to omit them, if indeed possible?

Thanks.

associated with

$
0
0

Hello.

I'm a CS student and taking C++ class.

This is my first question and I hope this put me on a good start in MSDN community. :)

I'm doing a homework experimenting with class hierarchy and data structures of bag and set.

I finally don't have compile errors but runtime errors.

The error details are as follows:

Unhandled exception at 0x00DB6577 in Assignment06.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD.

As I debug the break indicated this part of the code in the file Container.cpp :

Bag::~Bag() {
	cout << "deleting the bag" << endl;
	delete[] container;
}

with following details:

+ container0x00ea946c {name=0xdddddddd <Error reading characters of string.> age=-572662307 }Person *
+this0x00d7fbdc {size=1 capacity=10 container=0x00ea946c {name=0xdddddddd <Error reading characters of string.> ...} }Bag *

And the following is the whole code associated with this run.

// Container.h
#include "Person.h"
#define DEFAULT_CAP 50

class Bag
{
public:
	Bag(int capacity = DEFAULT_CAP);
	~Bag();
	void Add(Person p);
	Person* Delete();
	bool isEmpty() const;
	bool isFull() const;
	int currentSize() const;
	int Capacity() const;
	void Full();
	void Empty();

protected:
	int size;
	int capacity;
	Person* container;
};

class Set : public Bag
{
public:
	Set(int capacity = DEFAULT_CAP);
	~Set();
	void Add(Person p);
};

// Container.cpp

#include "Container.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

// Bag class methods

Bag::Bag(int max_capacity) {
	cout << "constructing the bag" << endl;
	capacity = max_capacity;
	size = 0;
	container = new Person[capacity];
}

Bag::~Bag() {
	cout << "deleting the bag" << endl;
	delete[] container;
}

void Bag::Add(Person p) {
	if (isFull())
		Full();
	else 
		container[size++] = p;
}

Person* Bag::Delete() {
	if (isEmpty()) {
		Empty();
		return NULL;
	}
	else {
		//generate a random number between 0 and (size - 1)
		int index = (int) rand() % size;
		Person* p = &container[index];
		container[index] = container[size - 1];
		size--;
		return p;
	}
}

bool Bag::isEmpty() const { return (size == 0); }

bool Bag::isFull() const { return (size == capacity); }

int Bag::currentSize() const { return size; }

int Bag::Capacity() const { return capacity; }

void Bag::Full()
{
	cout << "The container is full" << endl;
}

void Bag::Empty()
{
	cout << "The container is empty" << endl;
}


// Set class methods


Set::Set(int max_capacity) : Bag(max_capacity) {
	cout << "constructing the set" << endl;
}

Set::~Set() {
	cout << "deleting the set" << endl;
	delete[] container;
}

void Set::Add(Person p) {
	for (int i = 0; i < size; i++){
		if (container[i] == p){
			cout << "This person is already in the set" << endl;
			return;
		}
	}
	if (isFull())
		Full();
	else
		container[size++] = p;
}

// Person.h
#include <iostream>
#include <string>
using namespace std;

class Person
{
protected:
	char* name;
	int age;
public:
	Person() {}
	Person(char* n, int a) : name(n), age(a) 
	{
		cout << "I'm " << name << ", aged " << age << "." << endl;
	}
	virtual ~Person() {}
	char* Name() { return name; }
	int Age() { return age; }
	bool Person::operator == (const Person& other) const {
		if (strcmp(name, other.name) == 0 && age == other.age)
			return true;
		return false;
	}
};

class Employee : public Person
{
protected:
	char* position;
	int pay;
public:
	Employee() {}
	Employee(char* pos, int p) : position(pos), pay(p) {}
	virtual ~Employee() {}
	char* Position() { return position; }
	int Pay() { return pay; }
	void setPosition(char* c) { position = c; }
	void setPay(int i) { pay = i; }
};

class Student : public Person
{
protected:
	int s_num;
	char* major;
public:
	Student() {}
	Student(int s, char* m) : s_num(s), major(m) 
	{
		cout << "Student number : " << s_num << " ; major : " << major << endl;
	}
	virtual ~Student() {}
	int sNum() { return s_num; }
	char* Major() { return major; }
	void setSNum(int i) { s_num = i; }
	void setMajor(char* c) { major = c; }

	bool Student::operator == (const Student& other) const {
		if (s_num == other.s_num)
			return true;
		return false;
	}
};

class gradStudent : public Student 
{
protected:
	char* concentration;
public:
	gradStudent() {}
	gradStudent(char* c) : concentration(c) {}
	virtual ~gradStudent() {}
	char* Concentration() { return concentration; }
	void setConcentration(char* c) { concentration = c; }
};

class StudentWorker : public gradStudent, Employee
{
protected:
	int regist_num;
public:
	StudentWorker() {}
	virtual ~StudentWorker() {}
	int RegistNum() { return regist_num; }
	void setRegistNum(int i) { regist_num = i; }
};

class phdStudent : public gradStudent
{
public:
	phdStudent() {}
	phdStudent(Person(char* name, int age), Student(int sn, char* m), char* c) 
	{ 
		concentration = c; 
		cout << "I'm a PhD. Student concentrating on " << concentration << endl;
	}
	~phdStudent() {}

};

class phdWorker : public StudentWorker
{
protected:
	char* company;
public:
	phdWorker(Person(char* n, int a), Student(int sn, char* m), char* c)
	{
		company = c;
		cout << "I'm a PhD. student working for " << company << endl;
	}
	~phdWorker() {}
};

and the main

#include <iostream>
#include "Container.h"
using namespace std;

void main()
{
	Bag phdStds(10);
	Set phdWorks(10);

	cout << "Bag capacity : " << phdStds.Capacity() << endl;
	cout << "Set capacity : " << phdWorks.Capacity() << endl;

	phdStds.Add(Person("John", 11));
	phdWorks.Add(Person("Scala", 27));

}

As I give several variations to the codes, now I'm almost sure that the problem is happening when destructors are called. 

I learned some new things as follows:

  • 0xDDDDDDDD Used by MicroQuill's SmartHeap and Microsoft's C++ debugging heap to mark freed heap memory

But.... still this puzzle is out of my reach.

Please give me suggestions, concerns, and corrections as they come to you.

Thank you very much.

associated with

$
0
0

Hello.

I'm a CS student and taking C++ class.

This is my first question and I hope this put me on a good start in MSDN community. :)

I'm doing a homework experimenting with class hierarchy and data structures of bag and set.

I finally don't have compile errors but runtime errors.

The error details are as follows:

Unhandled exception at 0x00DB6577 in Assignment06.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD.

As I debug the break indicated this part of the code in the file Container.cpp :

Bag::~Bag() {
	cout << "deleting the bag" << endl;
	delete[] container;
}

with following details:

+container0x00ea946c {name=0xdddddddd <Error reading characters of string.> age=-572662307 }Person *
+this0x00d7fbdc {size=1 capacity=10 container=0x00ea946c {name=0xdddddddd <Error reading characters of string.> ...} }Bag *


And the following is the whole code associated with this run.

// Container.h
#include "Person.h"
#define DEFAULT_CAP 50

class Bag
{
public:
	Bag(int capacity = DEFAULT_CAP);
	~Bag();
	void Add(Person p);
	Person* Delete();
	bool isEmpty() const;
	bool isFull() const;
	int currentSize() const;
	int Capacity() const;
	void Full();
	void Empty();

protected:
	int size;
	int capacity;
	Person* container;
};

class Set : public Bag
{
public:
	Set(int capacity = DEFAULT_CAP);
	~Set();
	void Add(Person p);
};


// Container.cpp

#include "Container.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

// Bag class methods

Bag::Bag(int max_capacity) {
	cout << "constructing the bag" << endl;
	capacity = max_capacity;
	size = 0;
	container = new Person[capacity];
}

Bag::~Bag() {
	cout << "deleting the bag" << endl;
	delete[] container;
}

void Bag::Add(Person p) {
	if (isFull())
		Full();
	else 
		container[size++] = p;
}

Person* Bag::Delete() {
	if (isEmpty()) {
		Empty();
		return NULL;
	}
	else {
		//generate a random number between 0 and (size - 1)
		int index = (int) rand() % size;
		Person* p = &container[index];
		container[index] = container[size - 1];
		size--;
		return p;
	}
}

bool Bag::isEmpty() const { return (size == 0); }

bool Bag::isFull() const { return (size == capacity); }

int Bag::currentSize() const { return size; }

int Bag::Capacity() const { return capacity; }

void Bag::Full()
{
	cout << "The container is full" << endl;
}

void Bag::Empty()
{
	cout << "The container is empty" << endl;
}


// Set class methods


Set::Set(int max_capacity) : Bag(max_capacity) {
	cout << "constructing the set" << endl;
}

Set::~Set() {
	cout << "deleting the set" << endl;
	delete[] container;
}

void Set::Add(Person p) {
	for (int i = 0; i < size; i++){
		if (container[i] == p){
			cout << "This person is already in the set" << endl;
			return;
		}
	}
	if (isFull())
		Full();
	else
		container[size++] = p;
}


// Person.h
#include <iostream>
#include <string>
using namespace std;

class Person
{
protected:
	char* name;
	int age;
public:
	Person() {}
	Person(char* n, int a) : name(n), age(a) 
	{
		cout << "I'm " << name << ", aged " << age << "." << endl;
	}
	virtual ~Person() {}
	char* Name() { return name; }
	int Age() { return age; }
	bool Person::operator == (const Person& other) const {
		if (strcmp(name, other.name) == 0 && age == other.age)
			return true;
		return false;
	}
};

class Employee : public Person
{
protected:
	char* position;
	int pay;
public:
	Employee() {}
	Employee(char* pos, int p) : position(pos), pay(p) {}
	virtual ~Employee() {}
	char* Position() { return position; }
	int Pay() { return pay; }
	void setPosition(char* c) { position = c; }
	void setPay(int i) { pay = i; }
};

class Student : public Person
{
protected:
	int s_num;
	char* major;
public:
	Student() {}
	Student(int s, char* m) : s_num(s), major(m) 
	{
		cout << "Student number : " << s_num << " ; major : " << major << endl;
	}
	virtual ~Student() {}
	int sNum() { return s_num; }
	char* Major() { return major; }
	void setSNum(int i) { s_num = i; }
	void setMajor(char* c) { major = c; }

	bool Student::operator == (const Student& other) const {
		if (s_num == other.s_num)
			return true;
		return false;
	}
};

class gradStudent : public Student 
{
protected:
	char* concentration;
public:
	gradStudent() {}
	gradStudent(char* c) : concentration(c) {}
	virtual ~gradStudent() {}
	char* Concentration() { return concentration; }
	void setConcentration(char* c) { concentration = c; }
};

class StudentWorker : public gradStudent, Employee
{
protected:
	int regist_num;
public:
	StudentWorker() {}
	virtual ~StudentWorker() {}
	int RegistNum() { return regist_num; }
	void setRegistNum(int i) { regist_num = i; }
};

class phdStudent : public gradStudent
{
public:
	phdStudent() {}
	phdStudent(Person(char* name, int age), Student(int sn, char* m), char* c) 
	{ 
		concentration = c; 
		cout << "I'm a PhD. Student concentrating on " << concentration << endl;
	}
	~phdStudent() {}

};

class phdWorker : public StudentWorker
{
protected:
	char* company;
public:
	phdWorker(Person(char* n, int a), Student(int sn, char* m), char* c)
	{
		company = c;
		cout << "I'm a PhD. student working for " << company << endl;
	}
	~phdWorker() {}
};

and the main

#include <iostream>
#include "Container.h"
using namespace std;

void main()
{
	Bag phdStds(10);
	Set phdWorks(10);

	cout << "Bag capacity : " << phdStds.Capacity() << endl;
	cout << "Set capacity : " << phdWorks.Capacity() << endl;

	phdStds.Add(Person("John", 11));
	phdWorks.Add(Person("Scala", 27));

}

As I give several variations to the codes, now I'm almost sure that the problem is happening when destructors are called. 

I learned some new things as follows:

  • 0xDDDDDDDD Used by MicroQuill's SmartHeap and Microsoft's C++ debugging heap to mark freed heap memory

But.... still this puzzle is out of my reach.

Please give me suggestions, concerns, and corrections as they come to you.

Thank you very much.

Error TRK0002: failed to execute rc.exe (Visual Studio Express 2013)

$
0
0

Hi, I've been trying to build a project for several days now, and I can't fix this error.

I followed all the possibly related fixes that I found on the web, mostly consisting in moving files around, changing build/link properties, renaming folders, updating the version/going back to older versions of Visual Studio etc. Nothing worked at all. Most of the threads about related issues seem to have died without ever finding a solution.

Is there any precise method to fix this issue? Thanks.

Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>