fco*_*tes -1 c memory arrays objective-c char
我已经创建了下一个获取char*的代码,但是在执行此代码之后,finalResult的大小比预期的大,有一些垃圾字符.为什么??我该如何解决?
//returns void
void processChar(){
//.... more stuff here
// init is a previous char*
char* end = strstr(init,"</div>");
if(end != NULL){
long length = strlen(init) - strlen(end);
if (length > 0){
char* finalResult = malloc(length);
strncat(finalResult, init,length);
//these lengths are different,being strlen(finalResult) > length
NSLog(@"%d %d",strlen(finalResult),length);
//... more stuff here
}
}
return;
}
Run Code Online (Sandbox Code Playgroud)
这段代码:
char* finalResult = malloc(length);
strncat(finalResult, init,length);
Run Code Online (Sandbox Code Playgroud)
会给你一个不确定的结果.你试图拼接finalResult具有init,即使你从来没有初始化finalResult.也许你打算用strncpy()而不是strncat()?
而且,finalResult还不够大; 它还需要保存终止\0字符,因此您应该使用以下内容进行分配:
char* finalResult = malloc(length + 1);
Run Code Online (Sandbox Code Playgroud)
此外,正如Keith Thomson所指出的那样,要小心你使用它时的危险strncpy().
在这种特殊情况下,您可以strncpy()通过finalResult在分配之后简单地初始化为空字符串来避免使用,然后strncat()像以前一样使用:
char* finalResult = malloc(length + 1);
finalResult[0] = '\0';
strncat(finalResult, init, length);
Run Code Online (Sandbox Code Playgroud)
当然,您还应该检查malloc()内存不足错误的返回值,但这超出了您的问题的范围.