I'm fairly new with C. I have a function called kstrfrom that needs to create and return a new kstring object that contains a copy of the contents of a null-terminated C string, including the null terminator.
The .length member of the returned kstring should be the length of cstr, plus one for the null terminator. The .data member should be a pointer to newly-allocated memory, into which you have copied the contents of cstr, including the null byte at the end.
If there is an error allocating memory, this function should call abort() or throw an uncaught exception.
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;
}
I've ran a few test cases:
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)
As you can see I need help with giving correct link, containing correct data and copying data.
At the end of
while(*cstr!='\0')
{
cstr+=1;
length+=1;
}
You have lost the initial value of cstr
try
int length=1;
char * tmp = cstr;
while(*tmp!='\0')
{
tmp+=1;
length+=1;
}
You are not setting the length member...
cdest.length = length + 1;
Returning the kstring is problematic.
kstring res;
res = kstrfrom( "My String" ); /* works */
kstrfrom( "Another string" ); /* leaks memory */
Other comments are describing how you are ignoring language features. Your code can be achieved more easily with...
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.