问题大纠结 debug要用debug的库 release要用release库 没错 这就是vs2010

博客探讨了在VS2010中,直接使用`*names="dsfsdsfsd"`导致的非法内存访问异常。问题源于未通过构造函数初始化`Astring`对象,而是直接赋值,这触发了对象内部的清理过程,因对象未初始化而引发错误。解决方案是确保对象正确初始化后再进行赋值操作。
摘要由CSDN通过智能技术生成

先上两篇文章  再分析自己的:

http://blog.csdn.net/pcliuguangtao/article/details/5990561

C++中赋值和初始化不同“实例说明---欢迎大家发表自己的看法

#include
using namespace std;
class Astring
{
public:
    Astring(){s_=NULL;}
    Astring(const char *init);
    ~Astring();
    Astring(const Astring &that);
    Astring &operator=(const Astring &that);
    Astring &operator=(const char *str);
    friend ostream& operator<<(ostream&,Astring&);
    void swap(Astring &that);
private:
    Astring(const char*,const char *);
    char *s_;
};
ostream& operator<<(ostream& output,Astring& str)
{
   output<<STR.S_<<" n?;
   return output;
}
Astring::Astring(const char *init)
{
    if(!init) init="";
    s_=new char[strlen(init)+1];
    strcpy(s_,init);
}
Astring::~Astring()
{delete [] s_;}
Astring &Astring::operator=(const char *str)
{
    if(!str) str="";
    char *tmp=strcpy(new char[strlen(str)+1],str);
    delete [] s_;
    s_=tmp;
    return *this;
}

int main()
{
  Astring *names=static_cast(::operator new(100));
  *names="dsfsdsfsd";
  cout<<NAMES;
    return 0;
}

上面mian函数中*names="dsfsdsfsd";是有问题的,在vs2010里面原因是:

First-chance exception at 0x59eb59da (msvcr100d.dll) in test.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1.
Unhandled exception at 0x59eb59da (msvcr100d.dll) in test.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1.    非法访问内存地址!!!

但是我们已经定义了:Astring &Astring::operator=(const char *str),是因为赋值的时候会先清除左边的目标,然后再进行赋值;但是,我们直接使用的是new:

Astring *names=static_cast(::operator new(100));

并没有调用Astring的任何构造函数,即names并没有被初始化,但是*names="dsfsdsfsd"就会先删除*names里面的内容,所以出现错误。

 

改为下面的就可以了:

int main()
{
    Astring names;
    names="dsfsdsfsd";
    cout<<NAMES;
    return 0;
}

其中Astring names会默认调用

Astring(){s_=NULL;}构造函数,已经进行了初始化,所以可以成功的进行赋值。

 

http://social.msdn.microsoft.com/Forums/en-NZ/vcgeneral/thread/00ff8bf8-df4d-4d5f-ae72-d998165cee26

 

I have this:

char *something="thisthing";

char buffer[128]={0};

sprintf_s(buffer,128,"%s", something[0]); 
I get unhandled exception at some memory block. Access violation reading some memory location. The stack frame in VS shows _output_s_l() in output.c breaking at line 1643. Your input will be highly appreciated.

Signature series

Answers

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值