最近在使用string类时出现了一个问题,string *p=(string *)malloc(sizeof(string)*10);

来源:互联网 发布:cef chromium linux 编辑:程序博客网 时间:2024/06/03 17:52

            例子:

                   string *p=(string *)malloc(sizeof(string)*10);

                  *string str="tytyty";
                  *p=str;

                   free(p);

            将此段代码放入控制台程序的main()中运行,结果发生如下错误:Unhandled exception at 0x5958ca08 (msvcr100d.dll) in stringtest.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd.

            竟然发生了“

                  string *p=(string *)malloc(sizeof(string)*10);

                   memset(p,0,sizeof(string));

                  *string str="tytyty";
                  *p=str;

                  cout<<*p<<endl;.

                   free(p);

          结果输出为:"tytyty"。其实用malloc()给string分配内存是不好的,稍微不注意就会导致内存泄露!要知道string是c++ stl中的类,如果要为string进行内存分配的动作,最好使用new和delete的组合,这样又快又省事!

         所以说开头我使用malloc()为string类型的指针分配内存就是自找麻烦!实际上当使用malloc()为C的基本类型分配内存时,能很好地工作,也不存在必须要使用memset()为malloc()分配的int类型的内存区初始化,直接赋值就可以了。

        刚才又想了下,这个问题的关键是string *p=(string *)malloc(sizeof(string)*10);这句,只是说明p指向了一个可以容纳10个string类型的内存空间,这里面的值是随机的,不确定的,这和直接定义一个string对象不同,例如:string pp;这个系统自动为pp分配了一个string大小的内存,并且pp的初始值为"",然后我们才可以直接赋值给pp,反过来说,如果过pp的值如果像malloc()分配的string块的值一样,那么pp也不可以直接赋值,因个人能力有限不知道个中原因,但是起码也看到了这个表象。

       个人认为可以使用malloc()函数为C的基本类型分配内存,这个没有问题,如果用要为C++类型、包含有C++类型的结构体或者类分配内存,最好使用new分配,记得使用delete删除。虽然花大量时间思考了这个可以避免的问题,但是在过程中,我对C/C++的内存分配机制有了更深一层的认识。

0 0
原创粉丝点击