I’ve created the next code to obtain a char*, but after executing this code the size of finalResult is bigger than expected, with some garbage characters. Why?? How can I resolve it?
//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;
}
This code:
Will give you an undefined result. You’re trying to concatenate
finalResultwithinit, even though you never initializedfinalResult. Perhaps you meant to usestrncpy()instead ofstrncat()?Also,
finalResultis not big enough; it needs to also hold the terminating\0character, so you should allocate it with:Furthermore, as pointed out by Keith Thomson, beware of the dangers of
strncpy()when you’re using it.In this particular case, you can avoid using
strncpy()by simply initializingfinalResultas an empty string after you allocate it, and then usestrncat()as you did before:Of course you should also check the return value of
malloc()for out-of-memory errors, but this is outside the scope of your question.