Archived

This topic is now archived and is closed to further replies.

vbisme

Pointer Problem

Recommended Posts

vbisme    100
I want to make a class that contains a command line and parameters in characters:
  
#include <stdlib.h>
#include "hw1ldp_ccmd.h"

/////Constructor/////

cCmd::cCmd(short cmdsize, short params, short paramsize)
{
	pCmdLine = 0;
	pParam = 0;
	CmdSize = cmdsize;
	ParamCount = params;
	ParamSize = paramsize;

	Error = 0;
}
/////End Constructor/////


/////Destructor/////

cCmd::~cCmd()
{
	//--Free up memory--//

	delete pCmdLine;
	pCmdLine = 0;

	for (int i = 0; i< ParamCount; i++)
	{
		delete pParam[i];
		pParam[i] = 0;
	}//end for


	delete pParam;
	pParam = 0;
	//--//

}
/////End Destructor/////


void cCmd::SetMemory()
{
	pCmdLine = new char[CmdSize + 1];		//allocation command including null character

	if (!pCmdLine)
	{
		Error = 1;
	}
	
	pParam = (char **)calloc(ParamCount, sizeof(char*));	//allocate ParamCount pointers for

															//each parameter

	if (!pParam)
	{
		Error = 2;
	}
	//--Allocate ParamSize + 1 char for each parameter--//

	for (int i = 0; i < ParamCount; i++)
	{
		pParam[i] = new char[ParamSize + 1];
		if (!pCmdLine)
		{
			Error = 3;
			break;
		}
	}//end for

	//--//

}
  
Memory allocation is fine. But then the destructor is called to delete pParam my program crashes. What is wrong with my code?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
You''re mixing delete with calloc(). You need to use free().

Share this post


Link to post
Share on other sites