[英]Memory allocating and memory leaks: C
我對C相當陌生。我有一個名為kstrfrom的函數,該函數需要創建並返回一個新的kstring對象,該對象包含以null終止的C字符串(包括null終止符)的內容的副本。
返回的kstring的.length成員應為cstr的長度,再加上一個代表空終止符。 .data成員應該是指向新分配的內存的指針,您已將cstr的內容(包括末尾的空字節)復制到其中。
如果分配內存時出錯,則此函數應調用abort()或引發未捕獲的異常。
kstring kstrfrom(const char *cstr)
{
int length=1;
while(*cstr!='\0')
{
cstr+=1;
length+=1;
}
int i = 0;
kstring cdest={NULL,0};
cdest.data = malloc(length+1);
if(cdest.data == '\0')
{
abort();
}
else{
while(cstr[i] != '\0')
{
cdest.data[i] = cstr[i];
i++;
}
}
cdest.data[i] = '\0';
cdest.data[++i] = '\0';
return cdest;
}
我已經運行了一些測試用例:
Test 9/ 26: kstrfrom gives correct length skipped (0)
Test 10/ 26: kstrfrom contains null byte succeeded (1)
Test 11/ 26: kstrfrom contains correct data skipped (0)
Test 12/ 26: kstrfrom copies, not shares, data skipped (0)
如您所見,我需要有關給出正確鏈接,包含正確數據和復制數據的幫助。
在......的最后
while(*cstr!='\0')
{
cstr+=1;
length+=1;
}
您丟失了cstr的初始值
嘗試
int length=1;
char * tmp = cstr;
while(*tmp!='\0')
{
tmp+=1;
length+=1;
}
您未設置長度成員...
cdest.length = length + 1;
返回kstring有問題。
kstring res;
res = kstrfrom( "My String" ); /* works */
kstrfrom( "Another string" ); /* leaks memory */
其他評論描述了您如何忽略語言功能。 使用...可以更輕松地實現您的代碼。
kstring kstrfrom(const char *cstr)
{
kstring cdest={NULL,0};
cdest.data = strdup( cstr );
if( cdest.data == NULL ){
abort();
}
cdest.length = strlen( cstr ) + 1; /* not done in original example */
return cdest;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.