I have this line of code in my program which works fine except that the memory utilization is high I need to convert all parts to dynamic allocation but i have error at this line strcpy_s(p,sizeof(p), line.c_str());

the original code is :

ifstream  inFile1, inFile2;
      string pattern,text,line;

 
 
	  cout<<"Enter  file name.\n";
      cin>>pattern;
	  inFile1.open(pattern.c_str());
       if ( !inFile1 )
        {
          cout<<"Unable to open file. Enter a different name: ";
	      inFile1.clear();
          cin >> pattern;
	      inFile1.open(pattern.c_str());
	   }
      
	  char *p;
	  p = new char[500];

    while(getline(inFile1, line))
		  { 		
			strcpy_s(p, 500, line.c_str());
                           cout<<p; 			
	}

the modified code with errors :

Read the pattern file			
    while(getline(inFile1, line))
		  { 		
			  char* p = NULL;   
       
              p = new char[sizeof(line)];  
			  cout<< line.length().


			  strcpy_s(p,sizeof(p), line.c_str());
			
			cout<<p;

Recommended Answers

All 5 Replies

I have this line of code in my program which works fine except that the memory utilization is high I need to convert all parts to dynamic allocation but i have error at this line strcpy_s(p,sizeof(p), line.c_str());

the original code is :

ifstream  inFile1, inFile2;
      string pattern,text,line;

 
 
	  cout<<"Enter  file name.\n";
      cin>>pattern;
	  inFile1.open(pattern.c_str());
       if ( !inFile1 )
        {
          cout<<"Unable to open file. Enter a different name: ";
	      inFile1.clear();
          cin >> pattern;
	      inFile1.open(pattern.c_str());
	   }
      
	  char *p;
	  p = new char[500];

    while(getline(inFile1, line))
		  { 		
			strcpy_s(p, 500, line.c_str());
                           cout<<p; 			
	}

the modified code with errors :

Read the pattern file			
    while(getline(inFile1, line))
		  { 		
			  char* p = NULL;   
       
              p = new char[sizeof(line)];  
			  cout<< line.length().


			  strcpy_s(p,sizeof(p), line.c_str());
			
			cout<<p;

Hey. sizeof doesn't work on dynamic arrays (anything declared with new). The solution is to make a regular array[1024] or whatever the max line size is, then use sizeof on that, and use that number to declare your dynamic array.

I can't see the rest of your code but just remember to delete p each time if you have it inside a loop like that.

You are misusing the sizeof() operator. This operator is computed at compile-time, not at run-time. So, it cannot be used for getting the size of anything that was allocated dynamically (btw, dynamic is usually a synonym of "at run-time" in C/C++). Basically, it outputs the memory required to store the variable, at compile-time. In the case of a dynamically allocated array, that means the size of the pointer type, not the size of the array that it points to. This also goes for the string type (and equivalently C-style strings), sizeof() is not a proper way to get its size (as in, it's number of elements or characters).

So, at line 6 (in the erroneous code), the allocation should be p = new char[line.length() + 1]; (the + 1 is to store the null-character that terminates a C-style string), and, similarly, at line 10, you should have strcpy_s(p, line.length()+1, line.c_str()); (and it should also be that way on line 22 of the working code, even though it doesn't crash, you are doing useless copying of garbage data).

As Greywolf333 pointed out, don't forget to deallocate any memory you allocate with new (i.e. using delete[] p; ) once you are done with it of course.

I take it you are going to hold onto the string pointed to by p? Wny not make a copy of the source string as in a C++ string class object? In case you didn't know, I believe the string class uses a copy-on-write memory management algorithm, so if you don't modify the string, all you are getting is a pointer to the original - no actual allocation or copying done. There is rarely a reason to use C-style string pointers in C++. If you need to modify the contents of a string, pass it around by reference. If you only want to access or copy it, pass it around by const reference. Properly written, C++ is much more secure and in fact more efficient than all but the most carefully crafted C code. I've been a professional software engineer for 30 years, cut my teeth on C, and 20 years ago switch to C++ for major (10M loc) system development. Most of the stuff I've done since then couldn't be done in C, at least in the time frames I had to do it in. I still use C for kernel module and device driver development, but it's like going to the WC back in the 17th century - it's dark, dirty, nasty, and unsanitary! :-) FWIW, in that major system of 10M loc, we had ZERO deletes and no memory leaks because we "encouraged" our engineers to use our garbage-collecting smart pointers. Not having to worry about scoping of variables enabled us to deliver a system that runs most of the semiconductor factories in the world in a very (relatively) short period of time. These are systems that have to run 24x365 and downtime costs the customer about $10M per hour, so even 6-Sigma failure rates were too high!

commented: "6-Sigma failure rates were too high! " Holy macaronies!! +2

Thanks for all of you for the notes .
I tried the solution that you proposed but the progrma give some results then get out of memory !

this is the code after the modification.

cout<<"Enter text file name.\n";
      cin>>text;
	  inFile2.open(text.c_str());
       if ( !inFile2 )
        {
          cout<<"Unable to open file. Enter a different name: ";
	      inFile2.clear();
          cin >> text;
	      inFile2.open(text.c_str());
	   }

	   
	   
     wchar_t NameBuffer[10000];
     char* T = NULL; 
    //Read the pattern file			
	  while(getline(inFile2, line))
		  { 
			    
             
			T = new char[line.length() + 1]; 
			strcpy_s(T, line.length()+1, line.c_str());
			//	cout<<T<<endl;
     
			
            //convert char* to unicode

            string search1 = T;
            const size_t newsize1 = 500;
            size_t origsize = strlen(search1.c_str()) + 1;
            size_t convertedChars = 0;
            wchar_t wcstring1[newsize1];
            mbstowcs( wcstring1, search1.c_str(), newsize1); 
            
			//wcscat_s(wcstring1, L" (wchar_t *)");
			//wcout << wcstring1 << endl;
.     
.
.
delete [] T;  // When done, free memory pointed to by T.
T = NULL;     // Clear T to prevent using invalid memory reference.

>>Get Out of Memory?

I didn't understand what that actually means.

If you are trying to read a Wide Character formatted file. You might want to consider the wstring and wifstream classes in the Standard C++ Library.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.