مشکل در خطای سرریزی بافر

mhabat

Member
با سلام .سورسی که در زیر قرار داده شده مشکل سر ریزی بافر داره.
لطفا اگه میشه قسمت های زیر رو توضیح بدین:
کد:
using std::string; using std::cout; using std::endl;
و
کد:
char* bufferToCString(char *buff, int buffSize, char *str) {     memset(str, '\0', buffSize + 1);     return(strncpy(str, buff, buffSize)); }
مخصوصا این قسمتشو:
memset(str, '\0', buffSize + 1);
و
int main(int argc, char *argv[])

و
bufferToCString(buff, sizeof(buff), str)

سورس اصلی:
کد:
[COLOR=#808080]#include[/COLOR] [COLOR=#800000]<iostream>[/COLOR] 
[COLOR=#808080]#include[/COLOR] [COLOR=#800000]<string>[/COLOR] 
 
[COLOR=#00008b]using[/COLOR] std::string; 
[COLOR=#00008b]using[/COLOR] std::cout; 
[COLOR=#00008b]using[/COLOR] std::endl; 
 
 
[COLOR=#00008b]char[/COLOR]* bufferToCString([COLOR=#00008b]char[/COLOR] *buff, [COLOR=#00008b]int[/COLOR] buffSize, [COLOR=#00008b]char[/COLOR] *str) 
{ 
    memset(str, [COLOR=#800000]'\0'[/COLOR], buffSize + [COLOR=#800000]1[/COLOR]); 
    [COLOR=#00008b]return[/COLOR](strncpy(str, buff, buffSize)); 
} 
 
 
string& bufferToString([COLOR=#00008b]char[/COLOR]* buffer, [COLOR=#00008b]int[/COLOR] bufflen, string& str) 
{ 
    [COLOR=#00008b]char[/COLOR] temp[bufflen]; 
 
    memset(temp, [COLOR=#800000]'\0'[/COLOR], bufflen + [COLOR=#800000]1[/COLOR]); 
    strncpy(temp, buffer, bufflen); 
 
    [COLOR=#00008b]return[/COLOR](str.assign(temp)); 
} 
 
 
 
[COLOR=#00008b]int[/COLOR] main([COLOR=#00008b]int[/COLOR] argc, [COLOR=#00008b]char[/COLOR] *argv[]) 
{ 
   [COLOR=#00008b]char[/COLOR] buff[[COLOR=#800000]4[/COLOR]] = {[COLOR=#800000]'a'[/COLOR], [COLOR=#800000]'b'[/COLOR], [COLOR=#800000]'c'[/COLOR], [COLOR=#800000]'d'[/COLOR]}; 
 
   [COLOR=#00008b]char[/COLOR] str[[COLOR=#800000]5[/COLOR]]; 
   string str2; 
 
   cout << bufferToCString(buff, [COLOR=#00008b]sizeof[/COLOR](buff), str) << endl; 
 
   cout << bufferToString(buff, [COLOR=#00008b]sizeof[/COLOR](buff), str2) << endl; 
 
}
چه کار باید کرد تا بافر سر ریز بشود؟(این قسمتش خیلی برام مهم)
همچنین برای جلوگیری از این رخداد باید چه کار کرد؟
ممنون
 
آخرین ویرایش:

جدیدترین ارسال ها

بالا