Is this initialisation of a primitive variable correct? - iphone

I'm calling something like this kind of function here I have a variable named index I'm initiating it to 0 initially because I have a static analyzer leak in that initialization line. Is this the correct way of resolving that leak? Since I'm initiating to 0 and after my first if condition becomes true then again assigning to 0. Would this cause any problems?
-(NSString *)loadSelected:(NSString*)selectedOptn{
int index = 0;
if ([selectedOptn isEqualToString:#"A"]) {
index = 0;
}
else if([selectedOptn isEqualToString:#"B"]){
index = 1;
}
else if([selectedOptn isEqualToString:#"C"]){
index = 2;
}
else if([selectedOptn isEqualToString:#"D"]){
index = 3;
}
return [[array.options objectAtIndex:index] objectForKey:#"xyz"];
}

No, this won't cause any problems, I'm curious to know what the error was though - are you sure it wasn't just warning you that you hadn't initialised it or something?

Related

Swift - for loop statement not taking an absolute value

Such a weird question, but I set up this code in a playground:
let currentNumber = "1999999999"
let absNumber = abs(Double(currentNumber)!)
var digitCount = 0
if absNumber > 999999999 {
for n in currentNumber {
if n.isNumber {
digitCount += 1
} else {
break
}
print(digitCount)
}
}
As written, this code gets evaluated and my for loop runs...however, if is set my string to "-1999999999", the for loop doesn't run. The absolute value of -1999999999 is 100% greater than 999999999, so what did I miss?
The thing you did not understand is the control flow operator. You can get the expected behavior just change a single line:
if n.isNumber {
digitCount += 1
} else {
break // here change to continue
}
to this:
if n.isNumber {
digitCount += 1
} else {
continue
}
However, I highly recommend you try LLDB in an Xcode Project, either a Commandline tool or app. The stepover tool is quite useful for such a logical problem.

Index Out of Range Error in Swift

var numberOfPeople = 1 //get from host
var numberAtCounter = 0
func showNames() {
if peopleInMatch[numberAtCounter] == yourPeerID { //change to peopleinmatcheveryone
if numberOfPeople == 0 {
print("hoho")
personName.isHidden = true
connect.isHidden = false
connect.setTitle("PRESS READY", for: UIControlState.normal)
//change label to ready
} else {
numberAtCounter += 1
numberOfPeople -= 1 // buggy?
print("\(numberAtCounter)")
showNames()
}
} else {
personName.text = "TAKE PHOTO OF \(peopleInMatch[numberAtCounter])'s COLOR"
numberAtCounter += 1
if numberOfPeople <= 0 {
personName.isHidden = true
connect.isHidden = false
connect.setTitle("PRESS READY", for: UIControlState.normal)
//change label to ready
}
numberOfPeople -= 1 //buggy maybe fixed
}
}
I'm getting a Thread 1: EXC_BREAKPOINT error on the if peopleInMatch[numberAtCounter] == yourPeerID line. I'm not entirely sure what out of index means or what is potentially wrong. The code will be run through once then the function calls itself and on the second time through it breaks down on the line I mentioned above. I've checked all the variables and none of them are nill. Any ideas?
Here I made a short example for you to understand where your problem actually is.
ScreenShot 1:
Everything works fine when function is called for first time value at numberAtCounter is printed.
Here in first call either you are decrementing the value as numberAtCounter-=1 which take value from 0 to -1. Thus in second call when the function is called in line at:
if peopleInMatch[numberAtCounter] == yourPeerID // here you need to check value of `numberAtCounter`
make sure it's not getting a negative value or value more than your peopleInMatch array.
Thus if it becomes negative or more than count, result you will get as follows:

Crazy behavior when using compiler optimization

Execution of the following code runs to "!!!" when the compiler is optimized:
int test()
{
volatile uint32_t flag = 0; /* volatile doesnt matter */
flag = 3;
if (flag == 0 )
{
return 0; // !!!
}
else
{
return 1;
}
}
Compiler: IAR Studio C compiler; Platform: SAM4C microcontroller; medium level optimization
Of course, this is already a code, where the original problem has been boiled down.
I cannot understand what the compiler is doing here ...
On the other hand, this works as expected:
int test()
{
volatile uint32_t flag = 0; /* volatile doesnt matter */
int result = 0;
flag = 3;
if (flag == 0 )
{
result = 0;
}
else
{
result = 1; // !!!
}
return result;
}
I spent some more time and observed, that the function indeed returns 1, although the debugger stops at the line with "return 0;".
The problem I ran into was rather related to an uninitialized variable (outside the function), which is not automatically set to zero during optimization.
Apart from the strange behavior in the debugger, the function is correct. Unfortunately, the observation resulted in a misinterpretation.

Javascript create a function that returns a boolean value based on certain parameters

Thanks for taking the time to look at my problem. What I'm trying to do is create a javascript function that tests whether a sting is a particular length and also whether each element of that string can be found in another string. The function then needs to return a boolean value of either true or false depending on whether the string is valid.
Here's what I have:
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
function isValidGuess(inStr)
{ var valid;
var Str = inStr;
for (i=0; i<Str.length; i++)
{ if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES.length)
{ valid = true;
}
else
{ valid = false;
}
}
return valid;
}
This code is not working at all. It only returns false every time. Any help you could provide would be greatly appreciated. Thank you.
N_CHOICES.length return undefined, because variable N_CHOICES is number.
you have to change your condition to
if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES)

Unit test in xcode : inconsistent build result

Test Case '-[TestParse testParsing]' started.
/Developer/Tools/RunPlatformUnitTests.include: line 415: 3256 Segmentation fault "${THIN_TEST_RIG}" "${OTHER_TEST_FLAGS}" "${TEST_BUNDLE_PATH}"
/Developer/Tools/RunPlatformUnitTests.include:451: error: Test rig '/Developer/Platforms /iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/Developer/usr/bin/otest'
exited abnormally with code 139 (it may have crashed).
I got this seg fault message while I built test case randomly (sometime it built successfully, sometimes it throws seg fault). I'm not sure how I could fix this error.
Only thing I test here is I wrote one class name Parse with class level method. And in test case I just call it like
var = [Parse methodName:filepath];
method is like this
NSMutableDictionary *tempBox = [[NSMutableDictionary alloc] init];
FILE *fd = fopen([filePath UTF8String], "r");
if(!fd){
NSLog(#"fail to open file\n");
}
char buf[4096], *ptr;
char name[512], description[4096];
int isNewInfo = 2, description_continue = 0;
// for (line = 0; line < [args objectAtIndex:1]; line++) {
// fgets(buf, 4096, fd);
// }
while(fgets(buf, sizeof(buf), fd) != NULL){
if(strcmp(buf, "\n") == 0){
isNewInfo -= 1;
if(isNewInfo == 0){
isNewInfo = 2;
description_continue = 0;
description[strlen(description)-1] = '\0';
[self saveDrinkandResetBuf:name
detail:description box:tempBox];
if(name[0] != 0 || description[0] != 0){
NSLog(#"fail to reset...");
}
}
}
if(description_continue){
strcat(description, buf);
continue;
}
if((ptr = strstr(buf, "Drink Name: "))){
memcpy(name, buf+12, strlen(buf));
name[strlen(name)] = '\0';
continue;
}
if((ptr = strstr(buf, "Description: "))){
memcpy(description, buf+13, strlen(buf));
description_continue = 1;
continue;
}
}
fclose(fd);
NSLog(#"finish parsing section\n");
//[tempBox release];
return tempBox;
Not sure what is going on here..
I suppose, the problem is in array management.
In C if the array is declared in a function (and is not declared as a global or static one), then value of its elements is undefined. So your char description[4096] is filled with any values. And nobody said that '\0' will be there.
And the result of strlen(...) for non-null-terminated char string is not defined. It may result in a memory access violation, as it will keep counting until it reaches the first memory byte whose value is 0.
Moreover, when you call description[strlen(description)-1], strlen can return 0 (imagine that the first value, stored there initially was '\0' and your file was started with two empty lines [to reach this line of code]) - so array index will be -1...