tags:

views:

141

answers:

4

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?

+9  A: 

Actually the problem is strcpy(p,s1.c_str()); since p is never set to anything but NULL.

James Curran
@Zee99 strcpy just copies the data. p is a pointer to memory that is not allocated. Therefore when you copy you are just copying to memory location 0, which is illegal.
Romain Hippeau
+6  A: 

Remember that a char* is just an address of a memory location. You need to have memory allocated at the address.

In your code you don't have memory allocated to use and you didn't set p to point to that memory address.

strcpy does not allocate a buffer, it just takes a memory address to copy the data to.

If you are passing a buffer into the function then you probably want simply this (and remove p)

strcpy(lKey, s1.c_str());
Brian R. Bondy
+3  A: 

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.

Alexander Gessler
What if i want to perform some modifications on p and then assign it to lkey?let's say:i call methodone(p);and i then want to assign the result to lkey, how do i do that?
Zee99
+1  A: 
  1. Eliminate p (it is doing nothing here), and copy the data from s1 directly to lkey
  2. Not to beat on you, but the indentation scheme is a travesty, please cop a good style from somewhere ( google 1tbs )
jdu.sg