Thread: Problem with overwriting pointer

  1. #1
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001

    Problem with overwriting pointer

    ok, i have a problem with memory management in my program...and i'm not sure how to go about fixing it. From what i';ve picked up, declaring a pointer using new and an amount makes that memory dedicated to the pointer, however, if i write (say a string of 256 chars to a 256bit pointer) it doesn't overwrite, it spills into unclaimed memory. This won't cause immediate effects, but this program will be run constantly and the write will happen hundreds of thousands of times a day most likely. So that would be very very bad. I won't confuse you with the junk in my loop, but i'll convey the basic idea of what's wrong:
    Code:
    //////GLOBALS
    char * szBuffer=new char[256];
    
    int main()
    {
         while(bool something)
         {
              //windows read file operation here...reads 256 chars to szBuffer
              //something makes the loop continue or end
         }
    delete szBuffer[];
    szBuffer=NULL;
    }
    i first discovered the bug when the program closed, however i din't know what it meant (i now know what it does as i mentioned earlier)
    i found a work around which i used so i could show my boss that i hadn't worked on nothing for the last 2 weeks in which i made the pointer null before deleting. Basically it just makes windows miss the error, lol. So, i'd like your guru opinions on what to do.

    One thing i tried was deleting and nulling the pointer at the end of the loop each time then at the beginning of the loop if the pointer ! (didn't exist) then i'd recreate it with new...but that didn't work...so thanks for any help you can give me.
    PHP and XML
    Let's talk about SAX

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Can you show just a little bit more code.... like where you are putting data into the array, and reading from it.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    well without seeing how you actually fill the buffer and use it its hard to tell. You should always remember to delete anything that you've newed otherwise a memory leak will result.
    btw you are remembering if you new 256 chars then you should only fill with 255 because the last byte will be a '\0'
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  4. #4
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Make sure that you're actually copying data to the buffer and not just assigning a new value to the pointer.

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    sorry hammer was skinning up and replying slowly....

    btw ur delete is wrong.

    it should be

    delete[]szBuffer;
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  6. #6
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    stoned_coder:
    i typed that wrong, been a while since i did the c++ thing, but it is delete[] in my code

    everyone else:
    i'm posting the program code in this post...it's not too incredibly long....concentrate on the globals section...and the startSearch() function
    do note that i have null and delete[] reversed because this is what i compiled for my boss lol
    Code:
    /*BUGS AS OF AUGUST 2 2002:
    	
    	COMPLETE WORKING VERSION, NO BUGS...sort of
    */
    
    
    #include "stdafx.h"
    #include "Part Finder.h"
    
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // THE APPLICATION OBJECT
    
    CWinApp theApp;
    
    using namespace std;
    
    
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // FUNCTION PROTOTYPES
    int init(void);
    int mainMenu(void);
    int startSearch(void);
    int returnChoice(void);
    int ErrorHandler(string Error);
    
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // GLOBALS
    int nRetCode = 0;
    char choice[4];
    int company=25;
    bool goAgain=FALSE;
    bool stop=FALSE;
    char partNumber[25];
    char * currentDir=new char [MAX_PATH];
    char pathCommand[]="c:\\shop_machines\\puma_part_prg\\PUMA\\";
    char * szBuffer=new char[256];
    HANDLE hFileRead;
    HANDLE hSearchFile;
    WIN32_FIND_DATA fileData;
    char * tempFileName=new char[15];
    bool foundOnce=FALSE;
    bool stillFiles=TRUE;
    LPDWORD lpNumberOfBytesRead=new unsigned long;
    bool noChoice=TRUE;
    ofstream fout("c:\\Part Finder\\results\\results.txt");
    char * b=new char [sizeof(szBuffer)];
    int numOfResults=0;
    HWND hwnd;
    string ccompany;
    int infiniteLoopCount;
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // MAIN FUNCTION
    
    
    
    
    
    
    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
    
    
    
    	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    	{
    		ErrorHandler("\n\nProgram Initialization Failed");
    	}
    	else
    	{
    		//run the initial greeting 
    		init();
    		do{
    			//which company?
    			mainMenu();
    			//search here
    			startSearch();
    			//want to search again?
    			returnChoice();
    		}while(goAgain==TRUE);
    	}
    	//clean up memory
    	currentDir=NULL;
    	szBuffer=NULL;
    	tempFileName=NULL;
    	lpNumberOfBytesRead=NULL;
    	b=NULL;
    	delete [] szBuffer;
    	delete [] currentDir;
    	delete [] tempFileName;
    	delete [] b;
    	delete lpNumberOfBytesRead;
    	fout.close();
    	std::cout<<"Press Any Key To Quit"<<endl;
    	getch();
    	return nRetCode;
    }
    
    
    
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // PROGRAM FUNCTION DEFINITIONS
    
    
    
    int init(void){
    	system("cls");
    	std::cout<<"\nPart Finder Version 3.0\n\n";
    	std::cout<<"Copyright 2002\nCreated By Drew Peterson";
    	Sleep(4000);
    	system("cls");
    return 0;
    }
    
    
    
    
    
    
    
    int mainMenu(void){
    //company menu block,leave tabs alone!
    	if(goAgain==TRUE){		
    		strcpy(pathCommand,"c:\\shop_machines\\puma_part_prg\\puma\\");
    		numOfResults=0;
    	}
    
    
    	while(company>24&&infiniteLoopCount<10) {
    
    		std::cout<<"Which Company Is The Part For?"<<endl;
    		std::cout<<"		AMT		0"<<"	||	Mercury		13"<<endl;
    		std::cout<<"		Barber		1"<<"	||	Misc.		14"<<endl;
    		std::cout<<"		BeloitCP	2"<<"	||	Modern		15"<<endl;
    		std::cout<<"		Borg		3"<<"	||	Nissan		16"<<endl;
    		std::cout<<"		Bosch		4"<<"	||	Packard		17"<<endl;
    		std::cout<<"		Camcar		5"<<"	||	Phil		18"<<endl;
    		std::cout<<"		Colt		6"<<"	||	Simmons		19"<<endl;
    		std::cout<<"		Durst		7"<<"	||	SSI		20"<<endl;
    		std::cout<<"		Enkel		8"<<"	||	Tradewind	21"<<endl;
    		std::cout<<"		Goex		9"<<"	||	Warman		22"<<endl;
    		std::cout<<"		Isthmus		10"<<"	||	Warner		23"<<endl;
    		std::cout<<"		Kulasik		11"<<"	||	Witco		24"<<endl;
    		std::cout<<"		Lear		12"<<"	||"<<endl;
    		std::cout<<"\nEnter Choice Here:";
    		std::cin>>company,cin.get();
    		std::cin.clear();
    		infiniteLoopCount++;
    	}
    	if(infiniteLoopCount>=10)
    	{
    		system("cls");
    		ErrorHandler("Oh No!!!\nYou've Been Caught In The Infinite Loop Of Death!!!\n\nNext Time Enter The Number Of The Company, Have A Nice Day\n");
    	}
    
    	//with the below, fileFind will go to the correct directory
    	//when finding all the files...
    	//basically takes whatever pathCommand is now c:whatever to c:whatever whatever so you can search
    	switch(company){
    		case 0:
    			strcat(pathCommand,"Amt");
    			strcpy(currentDir,pathCommand);
    			ccompany="Amt";
    			break;
    		case 1:
    			strcat(pathCommand,"Barber");
    			strcpy(currentDir,pathCommand);
    			ccompany="Barber";
    			break;
    		case 2:
    			strcat(pathCommand,"Beloit");
    			strcpy(currentDir,pathCommand);
    			ccompany="BeloitCP";
    			break;
    		case 3:
    			strcat(pathCommand,"Borg");
    			strcpy(currentDir,pathCommand);
    			ccompany="Borg";
    			break;
    		case 4:
    			strcat(pathCommand,"Bosch");
    			strcpy(currentDir,pathCommand);
    			ccompany="Bosch";
    			break;
    		case 5:
    			strcat(pathCommand,"Camcar");
    			strcpy(currentDir,pathCommand);
    			ccompany="Camcar";
    			break;
    		case 6:
    			strcat(pathCommand,"Colt");
    			strcpy(currentDir,pathCommand);
    			ccompany="Colt";
    			break;
    		case 7:
    			strcat(pathCommand,"Durst");
    			strcpy(currentDir,pathCommand);
    			ccompany="Durst";
    			break;
    		case 8:
    			strcat(pathCommand,"Enkel");
    			strcpy(currentDir,pathCommand);
    			ccompany="Enkel";
    			break;
    		case 9:
    			strcat(pathCommand,"Goex");
    			strcpy(currentDir,pathCommand);
    			ccompany="Goex";
    			break;
    		case 10:
    			strcat(pathCommand,"Isthms");
    			strcpy(currentDir,pathCommand);
    			ccompany="Isthmus";
    			break;
    		case 11:
    			strcat(pathCommand,"Kul");
    			strcpy(currentDir,pathCommand);
    			ccompany="Kulasik";
    			break;
    		case 12:
    			strcat(pathCommand,"Lear");
    			strcpy(currentDir,pathCommand);
    			ccompany="Lear";
    			break;
    		case 13:
    			strcat(pathCommand,"Merc");
    			strcpy(currentDir,pathCommand);
    			ccompany="Mercury";
    			break;
    		case 14:
    			strcat(pathCommand,"Misc");
    			strcpy(currentDir,pathCommand);
    			ccompany="Miscellaneous";
    			break;
    		case 15:
    			strcat(pathCommand,"Modern");
    			strcpy(currentDir,pathCommand);
    			ccompany="Modern";
    			break;
    		case 16:
    			strcat(pathCommand,"Nissan");
    			strcpy(currentDir,pathCommand);
    			ccompany="Nissan";
    			break;
    		case 17:
    			strcat(pathCommand,"Pack");
    			strcpy(currentDir,pathCommand);
    			ccompany="Packard";
    			break;
    		case 18:
    			strcat(pathCommand,"Phil");
    			strcpy(currentDir,pathCommand);
    			ccompany="Phil";
    			break;
    		case 19:
    			strcat(pathCommand,"Simmon");
    			strcpy(currentDir,pathCommand);
    			ccompany="Simmons";
    			break;
    		case 20:
    			strcat(pathCommand,"Ssi");
    			strcpy(currentDir,pathCommand);
    			ccompany="SSI";
    			break;
    		case 21:
    			strcat(pathCommand,"Tradwin");
    			strcpy(currentDir,pathCommand);
    			ccompany="Tradewind";
    			break;
    		case 22:
    			strcat(pathCommand,"Warman");
    			strcpy(currentDir,pathCommand);
    			ccompany="Warman";
    			break;
    		case 23:
    			strcat(pathCommand,"Warner");
    			strcpy(currentDir,pathCommand);
    			ccompany="Warner";
    			break;
    		case 24:
    			strcat(pathCommand,"Witco");
    			strcpy(currentDir,pathCommand);
    			ccompany="Witco";
    			break;
    	}
    return 0;
    }
    
    
    
    
    
    
    
    int startSearch(void){
    	//reinitialize in case they searched again
    	stillFiles=TRUE;
    	foundOnce=FALSE;
    	infiniteLoopCount=0;
    	//get the partNumber to search through the text files for
    	std::cout<<"\nEnter Part Name Or Number"<<endl;
    	std::cin.getline(partNumber,75,'\n');
    	std::cin.clear();
    	fout<<"\n\n\n\nSearching For "<<partNumber<<" In "<<ccompany<<" Yeilded:\n\n";
    	std::cout<<"\nSearching";
    	for(int i=0; i<=3; i++)
    	{
    		Sleep(750);
    		std::cout<<".";
    	}
    	std::cout<<"\n\n\n\n";
    	Sleep(250);
    	
    
    	//make currentDir the default directory for the file functions to work in
    	if(SetCurrentDirectory(currentDir)==0){
    		ErrorHandler("\n\nUnable To Set Directory");
    	}
    	//find the first file with, store info on it in the fileData struct
    	hSearchFile=FindFirstFile("*",&fileData);
    	//get the filename of the particular file at this point
    
    
    	
    	
    	strcpy(tempFileName,fileData.cFileName);
    	FindNextFile(hSearchFile,&fileData);
    	strcpy(tempFileName,fileData.cFileName);
    
    				
    	CharUpper(partNumber);			
    	
    	CloseHandle(hFileRead);
    				
    				//NOW GO FIND SOME MORE
    				
    				
    	//this loop will stop when there are no more files in the current directory			
    	do{
    		//checks to see if there are files
    		if(FindNextFile(hSearchFile,&fileData)==0){
    			stillFiles=FALSE;
    			std::cout<<"\n\nSearch Complete"<<endl;;
    		}else{
    			stillFiles=TRUE;
    		}
    		if(stillFiles==TRUE)
    		{
    			strcpy(tempFileName,fileData.cFileName);
    					
    					//IF THERE ARE MORE FILES
    					
    	
    			//same as above
    			hFileRead = CreateFile(tempFileName,		   // open found file
    			GENERIC_READ,			   // open for reading 
    			FILE_SHARE_READ,		   // share for reading 
    			NULL,					   // no security 
    			OPEN_EXISTING,			   // existing file only 
    			FILE_ATTRIBUTE_NORMAL,	   // normal file 
    			NULL);					   // no attr. template 
    						
    			if (hFileRead == INVALID_HANDLE_VALUE) 
    			{ 
    				ErrorHandler("\n\nCould Not Open File");   // process error 
    			} 			
    			if(ReadFile(hFileRead,szBuffer,256,lpNumberOfBytesRead,NULL)==0){
    				ErrorHandler("\n\nCould Not Read File"); //process error
    			}else{
    				CharUpper(szBuffer);
    				b=strchr(szBuffer,'(');
    				if (b==NULL) {
    					stop=TRUE;
    				}else{
    					stop=FALSE;
    				}	
    				if (stop!=TRUE){
    					strtok(b,")");
    					b[0]='\b';
    				
    
    					if (strstr(b,partNumber)!=NULL) {
    						std::cout<<"That Part Was Found In: "<<currentDir<<'\\'<<tempFileName<<endl;
    						std::cout<<"\"\""<<b<<"\"\n"<<endl;
    						fout<<"That Part Was Found In: "<<currentDir<<'\\'<<tempFileName<<endl;
    						fout<<'\"'<<b<<"\"\"\n"<<endl;
    						foundOnce=TRUE;
    					}
    				}
    				CloseHandle(hFileRead);
    				numOfResults++;
    			}
    		}
    	}while(stillFiles==TRUE);					
    	FindClose(hSearchFile);
    	if(foundOnce==FALSE){
    		std::cout<<"That Part Number Was Not Found"<<endl;;
    		fout<<"That Part Number Was Not Found"<<endl;
    	}
    	if(numOfResults>=6){
    		ShellExecute(hwnd,"open","results.txt",NULL,"c:\\Part Finder\\results",SW_SHOWNORMAL);
    	}
    return 0;
    }
    
    
    
    
    
    
    
    
    
    int returnChoice(void){
    	//see if they want to run the program again
    	do{
    		std::cout<<"Do You Wish To Perform Another Search? (Y/N)"<<endl;
    		std::cin.getline(choice,3,'\n');
    		std::cin.clear();
    		if (choice[0]=='y'||choice[0]=='Y'){
    			goAgain=TRUE;
    			noChoice=FALSE;
    		}else if(choice[0]=='n'||choice[0]=='N'){
    			goAgain=FALSE;
    			noChoice=FALSE;
    		}else{
    			noChoice=TRUE;
    		}
    	}while(noChoice==TRUE);
    		company=25;
    		if(goAgain==TRUE){
    			system("cls");
    		}
    return 0;
    }
    
    
    
    
    
    int ErrorHandler (string Error){
    	//tell about errors , clean memory, and exit
    
    	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED|FOREGROUND_INTENSITY );
    	std::cout<<Error<<endl;
    	if(currentDir){
    		currentDir=NULL;	
    		delete [] currentDir;
    	}
    	if(szBuffer){
    		szBuffer=NULL;
    		delete [] szBuffer;
    	}
    	if(tempFileName){
    		tempFileName=NULL;
    		delete [] tempFileName;
    	}
    	if(lpNumberOfBytesRead){
    		lpNumberOfBytesRead=NULL;
    		delete lpNumberOfBytesRead;
    	}
    	if(b){
    		b=NULL;
    		delete [] b;
    	}
    	std::cout<<"Press Any Key To Quit"<<endl;
    	getch();
    	exit(1);
    }
    thanks again

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    1) In your example, you showed no good reason to be using dynamic memory. Just use a static array.
    2) The best way to discard dynamic memory is:
    if(ptr != NULL) {
    delete[] ptr;
    ptr = NULL;
    }
    3) Don't use "new". Overload it with malloc() and ditto for "delete" (use free()). Why? So you don't have to do:
    delete[] mem vs. delete mem, depending on the data.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  8. #8
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    ok, i have to use the pointer because of the windows function....if i use malloc() and i go to write to szBuffer as shown above (the actual program code) will it overwrite what i ahve their, or overflow like it's doing? All i'm really after is avoiding the aforementioned. thanks again.
    PHP and XML
    Let's talk about SAX

  9. #9
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    No, that's not right. Consider the following:

    void Print(char *ptr){
    cout << ptr;
    }

    char array[256];
    char dyn_array = new char [256];

    ...code...

    Print(array);
    Print(dyn_array);

    See? They are interchangeable. The name of a char array is basically a const pointer (meaning no incrementing it like a normal pointer, and no 'array = "hello;" ' usage. Plus storage was set aside for "array" within the executable (the stack). "dyn_array" requires that there is available memory "on the heap".

    Also:

    char * b=new char [sizeof(szBuffer)];

    sizeof(szBuffer) = 4 bytes, always!

    This quirk is very important. Had you done it on the static array I described, then sizeof(array) would be 256. Again, sizeof(dynarray) would be 4! The latter result will also occur with a static array passed to a function. Just try and see:

    void PrintSize(char *ar){
    cout << sizeof(ar);
    }

    char array[256];

    cout << sizeof(array); //...prints "256".

    PrintSize(array);...prints "4".
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  10. #10
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    ok, i've made the following changes in my code:
    Code:
    char szBuffer[256];
    char b[256];
    ...
    
    if(ReadFile(hFileRead,&szBuffer,255,lpNumberOfBytesRead,NULL)==0){
         ErrorHandler("\n\nCould Not Read File"); //process error
         }
    
    //removed deletes[] and nulls
    but now i'm having trouble with this:
    Code:
    b=strchr(szBuffer,'(');
    produces compiler error: error C2440: '=' : cannot convert from 'char *' to 'char [256]'
    There are no conversions to array types, although there are conversions to references or pointers to arrays

    so how do i work around that?
    PHP and XML
    Let's talk about SAX

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Smart compiler! You pointed that pointer to 256 bytes of memory, and then you try to assign it to the return value of strchr() without freeing the memory first. While this produces no errors on my compiler, it's plain bad programming. Just remember, a pointer is simply a handle. If you point it to allocated memory, that is your only connection to that memory. By doing:
    ptr = NULL;
    or...
    ptr = strchr(szBuf, '(');

    ...you are basically cutting away this connection, and the memory just "leaks".

    Anyway, the problem is solved by not doing such things, and so just make a pointer and use it for that return value.

    char *result = strchr(szBuf, '(');

    By the way, the standard library functions are not giving you a handle to new memory, so DON'T DELETE IT!! They are just giving you a pointer to some point within the string, ie:

    char buff[] = "hello!";
    char * third = &buff[2];

    printf("%s", third); //..prints: "llo"
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    okely dokely...i think i'm starting to get it, but it's always been kind of confusing to me. I've done the following changes:
    Code:
    //in globals i added this pointer:
    char * a=new char[256];
    //i delete and null it at program termination like so:
    delete [] a;
    a=NULL;
    //i use it like so, in conjunction with char b[256]
    CharUpper(szBuffer);
    a=strchr(szBuffer,'(');
    if (a==NULL) {
    stop=TRUE;
    }else{
    stop=FALSE;
    }	
    if (stop!=TRUE){
    strcpy(b,a);
    strtok(b,")");
    b[0]='\b';
    it compiled and ran fine...in debug mode there were no errors like there used to be...all my nulls and deletes have been put in proper order so im not fooling it....is it all right now?
    just in case i attached the whole source again.
    thank you very much, this has been bugging me for quite some time.
    PHP and XML
    Let's talk about SAX

  13. #13
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    char * a=new char[256];
    ...
    a=strchr(szBuffer,'(');

    That's a memory leak. "a" should be just an "empty" pointer. Change to:

    char * a = NULL;
    ...
    a=strchr(szBuffer,'(');

    Take this analogy. Imagine a pointer to be a cloth rope tied to an anchor on a cliff, a const pointer (such as the name of a static array) to be a steel rope anchored to the cliff. The steel ropes are attached to buckets, and cannot be untied from these buckets. The cloth ropes can be tied to new buckets, and they can be tied to existing buckets attached to both steel and cloth ropes. Allocated memory is a bucket tied to a cloth rope (let's just call them "new" buckets).
    Now then, if you have a cloth rope tied to a "new" bucket, but then decide to tie it to another bucket, whether new or existing, the first bucket will fall to the ground because you didn't take care of it before you tied the rope to something else! That's a memory leak. So the best rope to choose for that job would have been one that was not attached to anything (a null pointer).

    a=strchr(szBuffer,'(');

    This attaches "a" to some point in the array szBuffer. Following the above analogy, szBuffer is a bucket attached to a steel rope, and "a" is a cloth rope tied to that same bucket. You can untie "a" an any convenient time since the steel rope (the word "szBuffer") will remain.

    char array[] = "man";
    char * a = &array[2];
    *a = 'p';

    printf("%s", array); //...prints "map" instead of "man"

    I hope that helps.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  14. #14
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    thank you very much
    it actually all makes sense now, i printed that post and it's now stapled to my wall. thanks again.
    PHP and XML
    Let's talk about SAX

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to pointer realloc problem
    By prakash0104 in forum C Programming
    Replies: 14
    Last Post: 04-06-2009, 08:53 PM
  2. Another pointer problem
    By mikahell in forum C++ Programming
    Replies: 21
    Last Post: 07-20-2006, 07:37 PM
  3. Pointer problem
    By mikahell in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2006, 10:21 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. pointer problem
    By DMaxJ in forum C Programming
    Replies: 4
    Last Post: 06-11-2003, 12:14 PM