Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy char* to char*

Tags:

c++

char

Here is part of my code:

extern "C" REGISTRATION_API int extreme(char* lKey)
{
string s1; 
char *p=NULL;
try
{
    ifstream myfile ("extreme.txt");
    int i=0;
    if (myfile.is_open())
    {
    while (getline(myfile,s1))
       {
        switch (i)
         {
        case 1:
         strcpy(p,s1.c_str());
         lKey=p;
        break;
             //continue here
         }
      }
   }
}

Now when I call this function from external application, I get this error:

AccessViolationException:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The problem is due to this:

lKey=p;

How can I assign the lKey to p?

like image 683
Zee99 Avatar asked Jul 15 '10 14:07

Zee99


1 Answers

You need to pre-allocate the memory which you pass to strcpy. I.e. a p = new char[s1.length()+1]; will do it (+1 for the terminating 0 character). However, it's not a good idea to mix up std::string and C string routines for no good reason. Better stick with std::string, it will save you a LOTS of trouble.

Also lKey=p won't work either -- it just copies the local address of p into the local variable lKey. The caller won't even see a difference.

like image 137
Alexander Gessler Avatar answered Oct 03 '22 03:10

Alexander Gessler