• c++ string memcpy


    //----------------------------------------------------

    //AUTHOR: lanyang123456

    //DATE: 2014-10-30

    //---------------------------------------------------


    /*
    str5.cpp
    $ g++ -o test str5.cpp
    OS Ubuntu
    */

    #include <string>
    #include <iostream>

    #include <string.h>
    #include <stdio.h>

    using namespace std;

    int main()
    {
    string t1("123456789");
    string t2;

    cout<<"t1 string:"<<t1<<endl;
    printf("t1 string:%s ",t1.c_str());//返回一个以null终止的c字符串
    printf("sizeof t1 = %lu ", sizeof(t1));
    printf("t1.capacity = %lu ", t1.capacity());//返回当前容量(即string中不必增加内存即可存放的元素个数)
    printf("t1.max_size = %lu ", t1.max_size());//返回string对象中可存放的最大字符串的长度
    printf("t1.size = %lu ", t1.size());//返回当前字符串的大小
    printf("t1.length = %lu ", t1.length());//返回当前字符串的长度

    memcpy(&t2, &t1, sizeof(t1));//problem

    cout<<"t2 string:"<<t2<<endl;
    printf("t2 string:%s ",t2.c_str());//返回一个以null终止的c字符串
    printf("sizeof t2 = %lu ", sizeof(t2));
    printf("t2.capacity = %lu ", t2.capacity());//返回当前容量(即string中不必增加内存即可存放的元素个数)
    printf("t2.max_size = %lu ", t2.max_size());//返回string对象中可存放的最大字符串的长度
    printf("t2.size = %lu ", t2.size());//返回当前字符串的大小
    printf("t2.length = %lu ", t2.length());//返回当前字符串的长度

    return 0;
    }

    $ ./test
    t1 string:123456789
    t1 string:123456789
    sizeof t1 = 4
    t1.capacity = 9
    t1.max_size = 1073741820
    t1.size = 9
    t1.length = 9
    t2 string:123456789
    t2 string:123456789
    sizeof t2 = 4
    t2.capacity = 9
    t2.max_size = 1073741820
    t2.size = 9
    t2.length = 9
    *** Error in `./test': double free or corruption (fasttop): 0x08120008 ***
    Aborted (core dumped)

    字符串真是存放地址如下:

  • 相关阅读:
    python笔记005-字符串-列表-元组
    Python笔记2 标准数据类型
    VS2010与VAssistX
    【Windows核心编程】Windows常见数据类型
    网络安全加密
    防御 XSS 的七条原则
    用户权限初略设计
    [Android]Handler的消息机制
    java的线程中的Runnable
    [转]永久告别Android的背景选择器Selector!无需切很多图了!
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15457721.html
Copyright © 2020-2023  润新知