Click here to Skip to main content
15,849,163 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

This is a simple set Function, I am trying to set a string from one class to another class using a simple function.

C++
void setStringVariable(string stringtext)
{
   m_stringTest = stringtext;
}

When I call the function, I get ACCESS_VIOLATION ERROR.
I am confused, what is going wrong?

Any Help.
Posted
Updated 4-Dec-12 10:33am
v2
Comments
André Kraak 4-Dec-12 15:36pm    
How are you calling the setStringVariable function?
gssajith87 4-Dec-12 15:57pm    
setStringVariable is in a class as public member, i am calling using the object of the class.
André Kraak 4-Dec-12 16:00pm    
Which specific call off the function is causing the problem?
What is the parameter you are passing to the function at that moment?
Sergey Alexandrovich Kryukov 4-Dec-12 16:11pm    
Also, is it std::string, or something else?
Why having this function at all? Strings are assignable without the help of such function. :-)
--SA
JackDingler 4-Dec-12 16:23pm    
Which line is it failing on?

Are you crossing DLL boundaries?

Thanks All, i finally got it fixed, i changed setStringValue to take char * as argument.

C++
char *buff;

void setStringValue(char *buffText)
{
  buff = new char[strlen(buffText)+1];
  memset(buff, 0, strlen(buffText) +1);
  memcpy(buff, buffText, strlen(buffText));
}


Note to delete the buff in the destructor of the class
 
Share this answer
 
Comments
Stefan_Lang 5-Dec-12 4:31am    
Have you considered the possibility that the cause of that access violation is passing a NULL pointer to setStringValue? Doing so will not break the code you posted here, but it will still cause unexpected behaviour!
gssajith87 5-Dec-12 9:42am    
@Stefan_Lang, It was not the NULL pointer i was passing to, have verified the same.
Your original code should work unless the parameter you are passing to the setStringValue function is a private datamember of some other class.
 
Share this answer
 
Comments
gssajith87 5-Dec-12 9:46am    
Hi, the same call from another function works fine, when i call it from the second function, the ACCESS_VIOLATION comes in, in all the ways, both call is similar, but fails in the second. Not able to find the reason for crash, it was weird.
gssajith87 5-Dec-12 9:52am    
And one more information, as u asked, the variable that i am calling is a local variable of the calling function
Aswin Waiba 6-Dec-12 1:04am    
Try this

void setStringValue(string stringText)
{
if(stringText.length())
m_stringTest = stringText;
else
cout<<"error";
}

This should make it clear if you're passing a corrupted string.
gssajith87 7-Dec-12 12:35pm    
Thanks Aswin, I tried the same , still had issues.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900