Memcpy,字符串和终止符 [英] Memcpy, string and terminator

查看:918
本文介绍了Memcpy,字符串和终止符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个函数,用一个字符串的内容填充一个char *缓冲区为指定的长度。如果字符串太长,我只需要剪切它。缓冲区不是由我分配的,而是由我的函数的用户分配的。我试着这样:

I have to write a function that fills a char* buffer for an assigned length with the content of a string. If the string is too long, I just have to cut it. The buffer is not allocated by me but by the user of my function. I tried something like this:

int writebuff(char* buffer, int length){
    string text="123456789012345";
    memcpy(buffer, text.c_str(),length);
    //buffer[length]='\0';
    return 1;
}


int main(){
    char* buffer = new char[10];
    writebuff(buffer,10);
    cout << "After: "<<buffer<<endl;
}

我的问题是关于终止符:应该存在还是不存在?这个函数在一个更宽泛的代码中使用,有时候,当字符串需要剪切时,我似乎遇到奇怪的字符的问题。

my question is about the terminator: should it be there or not? This function is used in a much wider code and sometimes it seems I get problems with strange characters when the string needs to be cut.

有关正确程序的任何提示?

Any hints on the correct procedure to follow?

推荐答案

C风格字符串必须以零字符'\0'终止。

A C-style string must be terminated with a zero character '\0'.

此外,你有你的代码的另一个问题 - 它可以尝试从源字符串的末尾复制。这是经典的未定义的行为。它可能看起来像它的工作,直到一次的字符串分配在堆内存块的结尾,副本进入内存的保护区,并失败壮观。您只能复制到缓冲区长度的最小值或字符串的长度。

In addition you have another problem with your code - it may try to copy from beyond the end of your source string. This is classic undefined behavior. It may look like it works, until the one time that the string is allocated at the end of a heap memory block and the copy goes off into a protected area of memory and fails spectacularly. You should copy only until the minimum of the length of the buffer or the length of the string.

为了完整性,这里是一个很好的版本的函数。感谢 Naveen 指出您的终止中的一个错误空值。我已经自由使用你的返回值来表示返回的字符串的长度,或者如果传入的长度为<= 0,则需要的字符数。

P.S. For completeness here's a good version of your function. Thanks to Naveen for pointing out the off-by-one error in your terminating null. I've taken the liberty of using your return value to indicate the length of the returned string, or the number of characters required if the length passed in was <= 0.

int writebuff(char* buffer, int length)
{
    string text="123456789012345";
    if (length <= 0)
        return text.size();
    if (text.size() < length)
    {
        memcpy(buffer, text.c_str(), text.size()+1);
        return text.size();
    }
    memcpy(buffer, text.c_str(), length-1);
    buffer[length-1]='\0';
    return length-1;
}

这篇关于Memcpy,字符串和终止符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆