[Beginner Thread] Issue with "string" handling and memory leaks

This is a discussion on [Beginner Thread] Issue with "string" handling and memory leaks within the C++ Programming forums, part of the General Programming Boards category; Hi guys. I am a beginner in c++ programming learning all by myself. FYI i have started a 2 yrs ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    29

    Question [Beginner Thread] Issue with "string" handling and memory leaks

    Hi guys. I am a beginner in c++ programming learning all by myself. FYI i have started a 2 yrs ago programming in delphi. Mostly using API and my requirements being writing smaller apps and more optimised ones i decided to start writing code in C++. I am not a complete noob in programming but C++ is totally different from what i have been doing yet.

    The master difference in using c++ and delphi have been for me that "strings" are managed in a totally different way. Memory management is ... obviously totally different too. I am a google fan so i did a bit of researching before posting here. but still i am quite confused.

    I am going to give a brief example of what i am struggling to do. In delphi we normally write code this way.

    Code:
    Function SomeRandomThing(a,b :string):String;
    var x:string;
    begin
    x:='Garbage' + a + ' Some other garbage';
    result := x + b;
    end;
    My main issue now is that c++ doesnt have (or i am not aware of) automatic memory management. The following code segment is part of a little application i am trying to code. All this does is try to return a listing of files in a current directory. However there is a huge problem. or many look below.

    Code:
    char* DirList(char *path) 
    {
    	char *FileList = new char[10000];
    	char *temppath = new char[strlen(path) + 4];
    
    	char *tmpstr;
    	WIN32_FIND_DATA DataStruct;	
    	
    	HANDLE FindHandle;
    	
    	strcpy(FileList,path);
    	strcat(FileList,"\r");
    	
    	strcpy(temppath,path);	
    	strcat(temppath,"*.*");	
    			
    	FindHandle = FindFirstFile(temppath, &DataStruct);
    	if (FindHandle == INVALID_HANDLE_VALUE)
    		{
    			return "!Invalid Directory";
    			
    		}																
    	do
    		{
    			tmpstr = DataStruct.cFileName;
    			if ((strcmp(DataStruct.cFileName,".") != 0 ) && (strcmp(DataStruct.cFileName,"..") != 0 ))
    			{
    
    			if ((DataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    				{
    				strcat(FileList,"\\");
    				}
    			
    			strcat(FileList,DataStruct.cFileName);
    			strcat(FileList,";");
    			strcat(FileList,IntToStr(DataStruct.nFileSizeLow));
    			strcat(FileList,"\r");
    			}
    		}while((FindNextFile(FindHandle,&DataStruct)) != false);
    	FindClose(FindHandle);
    	
    	
    
    	char * result = new char[strlen(FileList) + 13];
    	strcpy(result,CMD_DIRECTORY_INFO);
    	strcat(result,IntToStr(strlen(FileList)));
    	strcat(result,"#");
    	strcat(result,FileList);
    	
    	free(temppath);
    	free(FileList);
    
    
    	return result;
    }
    Code:
    char *FileList = new char[10000];
    i am creating a new variable with size 10000, this is incorrect since. my file list will sometime either exceed this and most of the time be much below that. i should have a calculated array size b but it seems malloc and realloc crash on me

    Code:
    strcpy(result,CMD_DIRECTORY_INFO);
    strcat(result,IntToStr(strlen(FileList)));
    strcat(result,"#");
    strcat(result,FileList);
    is relatively tedious if i have to concat many strings... is there a shorter way?

    After running this code (yes it actually works) i get BIG memory leaks. but... i cleared my variables.

    Code:
    free(temppath);
    this gives me the same result...
    Code:
    delete[] temppath;
    what am i doing wrong?

    I am thinking about using a replacement class for this. but again size is an issue. std::string wont work for me since my application needs to be tiny. my objective is 10kb max.

    thanks in advance for your help.

  2. #2
    Supermassive black hole cboard_member's Avatar
    Join Date
    Jul 2005
    Posts
    1,709
    Using the standard library string class will help - it automatically manages the memory side of things for you and (IIRC) you can concatenate strings with the '+' operator.
    Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife.

    - Mike McShaffry

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    29
    i cant use that for many reasons one being size. do u know of a string replacement class that is small and as complete as possible? remember my app should be below 10kb.

  4. #4
    Supermassive black hole cboard_member's Avatar
    Join Date
    Jul 2005
    Posts
    1,709
    Sorry I don't. You could write your own but someone else must know if there's another.
    Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife.

    - Mike McShaffry

  5. #5
    Registered User
    Join Date
    Jan 2006
    Posts
    29
    well i wish i could but again... im not reinventing the wheel. there must exist someone who coded something for that matter. and since i am not grasping the concepts i cant do it i hope someone comes to my rescue here.

  6. #6
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    I get no memory leaks using that code if I just delete [] result in the calling code, ie:
    Code:
    char* result = DirList("c:\\documents and settings\\");
    delete [] result;
    Since you are using new you should also use delete (not free, although I don't get any memory leaks the way you have it).

    Oh yes, you probably have to change "\r" to "\n"
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  7. #7
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    >> is relatively tedious if i have to concat many strings... is there a shorter way?

    sprintf could work in this situation. As JaWiB said, use delete[] when memory is allocated with new[], not free().

    >> I am thinking about using a replacement class for this. but again size is an issue.

    Why is size an issue anyways? Static linkage of the standard C++ library when using STL functions makes the enourmous executable, but I understand that you do not want to re-invent the wheel. See this page for other non-STL string wrappers: http://www.codeproject.com/string/

  8. #8
    Registered User
    Join Date
    Jan 2006
    Posts
    29
    Quote Originally Posted by JaWiB
    I get no memory leaks using that code if I just delete [] result in the calling code, ie:
    Code:
    char* result = DirList("c:\\documents and settings\\");
    delete [] result;
    Since you are using new you should also use delete (not free, although I don't get any memory leaks the way you have it).

    Oh yes, you probably have to change "\r" to "\n"
    thanks for you replies.

    Yes Im not sure where or how but... i have tried doing a 100 time loop of a MessageBox with the result, over the 100 loops memory usage increases normally by 4-8k (Task Manager) but doesnt decrease again, i beleive there are more memory leaks in my program but again... i have been using the same type of new[] and delete[] strangely... memory usage tends to increase... not by much but still...
    Basically this function is part of a much larger application(still in the works). Might you have guessed a client server application. "/r" is just a character i use a terminator... i also use "/n" but in other circumstances. The client server application was written before in pure delphi. It was a quite complex server system but i want yet to improve it. I have been suggested to pass my socket to the function and avoid returning and working with new chars BUT this is to become a very complex project (i like learning this way) i will be using later on encryption\compression on my send(). This project is basically a test project. A starter for me to learn c++, my later aim is to learn to code "device drivers" in which i dont have the slightest idea but for now ... i will try mastering c++ techniques. Size is an issue because i have abandonned using delphi for that reason. my server in delphi weighted 90kb FAR too much for my taste. However delphi is THE BEST when it comes to GUI programming, it is 100 times simpler, than c++. a gui application can be coded in minutes. fyi i finished a basic server that accepted connections and displayed the output in a textbox in approximately 30 seconds. I need my application to be as FAST as possible (and yes i am considering learning asm but for now i will stick to c++) as SMALL as possible. And as memory effective as we can get. The reason being: it should be able to run on a 166Mhz processor without affecting the user. Or him noticing\complaining about any change. It should be compatible with winALL systems. I have 3 computers for my personal usage, and 2 more for my dad and my sister. my current coding box is a 433Mhz Celeron with 196MB Ram(Reason being if it works on my box it will be better on other boxes), this application should NOT eat my memory and performance should be comparable with what i get using the other pcs in my LAN. Target OS's being win98, winxp, win2k3.

    Thanks for the sprintf tip, very useful. Concerning the string replacement options ... please note that i am not familiar with c++ coding, i have yet to understand and learn the differences between the different application formats. MFC and STL are just weird words for the moment... could you point me to which string replacement class would suit my needs?

  9. #9
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    >>Might you have guessed a client server application. "/r" is just a character i use a terminator...
    Oh, that makes sense. I didn't even think of that

    I'm not sure why task manager reports that memory usage, but I don't think it has anything to do with this code. I used the CRT debug library provided for Visual Studio [msdn] to check that the memory is freed and it reported no memory leaks after running your code.
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. exception handling, function call and memory
    By George2 in forum C++ Programming
    Replies: 21
    Last Post: 01-30-2008, 07:00 AM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  3. Dynamic memory allocation for file handling
    By prashanth_sh in forum C Programming
    Replies: 2
    Last Post: 11-07-2002, 04:50 AM
  4. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21