sprintf的缓冲区溢出导致Segmentation fault (core dumped)

时间:2022-08-30 06:58:44
#include <iostream>
#include <stdio.h>                                                                                                                    
using namespace std;

int main()
{
    string strTest = "Hands cling to hands and eyes linger on eyes:thus begins the recond of our hears.It is the moonlit night of Marc
h;the sweet smell henna is in the air;my flute lies on the earth neglected and your garlang of flowers in unfinished.This lovebetween 
you and me is simple as a song.Your veil of the saffron colour makes my eyes drunk.The jasmine wreath that you wove me thrills to my h
eart like praise.It is a game of giving and withholding,revealing ane screening again;some smiles and some little shyness,and some swe
et useless struggles.This love between you and me is simple as a song.";

    char pbuf[250];
    sprintf(pbuf, "qid=[%lu];word=[%s] from UI", 1086, strTest.c_str());
        
    return 1;
}

执行时会core dump:Segmentation fault (core dumped)

原因是上述sprintf函数导致sprintf的缓冲区溢出,进而造成内存的破坏,解决方案是使用snprintf函数。

 

int snprintf(char *str, size_t size, const char *format, ...);

将可变个参数(...)按照format格式化成字符串,然后将其复制到str中,返回写入str中的字符串的长度。

(1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符('\0');

(2) 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符('\0')

 

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    string strTest = "Hands cling to hands and eyes linger on eyes:thus begins the recond of our hears.It is the moonlit night of Marc
h;the sweet smell henna is in the air;my flute lies on the earth neglected and your garlang of flowers in unfinished.This lovebetween 
you and me is simple as a song.Your veil of the saffron colour makes my eyes drunk.The jasmine wreath that you wove me thrills to my h
eart like praise.It is a game of giving and withholding,revealing ane screening again;some smiles and some little shyness,and some swe
et useless struggles.This love between you and me is simple as a song.";

    char pbuf[250];
    int nLength = snprintf(pbuf, 250, "%s", strTest.c_str());
    cout << nLength << endl;
    cout << pbuf << endl;
                                                                                                                                      
    return 1;
}

 

返回的结果为:

584
Hands cling to hands and eyes linger on eyes:thus begins the recond of our hears.It is the moonlit night of March;the sweet smell henna is in the air;my flute lies on the earth neglected and your garlang of flowers in unfinished.This lovebetween you

 

疑问:为什么snprintf函数的返回值为584?