Swift: UnsafeBufferPointer when using larger offset values in String.index(_:Int) - swift

I have the following line of code that sets a String.Index to a certain value using the index offset function in the swift standard library
index = str.(index, offsetBy: -length)
it functions for short str, but as soon as it, or the length value get above some arbitrary (and changing!) threshold, I get a variety of crashes. Most consistently, and from a break point is
Swift/UnsafeBufferPointer.swift:913: Fatal error
I have done a little research plus my own testing and have not found anything conclusive so far. The most helpful test I ran was trying to offset this index in smaller increments with a loop such as with the following code
for _ in 0...Int(totalLength) {
let newIndex = str(index, offsetBy: -1)
index = newIndex
}
however, the let newIndex line still crashed even with the offset value at 1, so I imagine that it is the cause of the long string. However, with this test I was more consistently getting BAD ACCESS errors instead of the UnsafeBufferPointer.
I have not found anyone online who has run into a similar problem, and am wondering if this is a documented issue with the function, or if there is some other thing at fault. Any help is appreciated, thank you !

Related

bypassing exc_breakpoint crash to continue program execution

During testing my iOS app, (it's a workout app), the app crashed (EXC_BREAKPOINT) as it was trying to save the workout data.
The crash was an index out of range issue whereby the array count is 1 lesser than the workout seconds. (I should have started the seconds counter from 1 instead of 0)
for i in 0...seconds {
let data = "\(i),\(dataArray.powerGenY[i-1]),\(dataArray.powerGenYAlt[i-1])\n"
do {
try data.appendToURL(fileURL: fileURL)
}
catch {
print("Could not write data to file")
}
}
anyways, the error dropped me to LLDB. Is there any way I an Use LLDB to bypass this error and continue execution?
Having worked out for a hour, I wasn't prepared to have this crash take my data along with it. Since the crashed dropped me into LLDB, I wanted to see if there's any way to salvage the data by stepping over / bypassing / changing the value of i so that the program execution can continue.
Initially I tried
(lldb) po i = 3327
error: <EXPR>:3:1: error: cannot assign to value: 'i' is immutable
i = 3327
^
but it won't let me change the value (I is immutable)
Then I tried thread jump -l 1 but it spewed some error about not the code execution outside of current function.
(lldb) th j -l 29
error: CSVExport.swift:29 is outside the current function.
Finally, going thru this site https://www.inovex.de/blog/lldb-patch-your-code-with-breakpoints/ and trying a few things. The one that helped was thread jump
thread return
The mentioned disadvantage of thread jump can be avoided by using a
different technique to change control flow behaviour. Instead of
manipulating the affected lines of code directly the idea is to
manipulate other parts of the program which in turn results in the
desired behaviour. For the given example this means changing the
return value of can_pass() from 0 to 1. Which, of course, can be done
through LLDB. The command to use is thread just like before, but this
time with the subcommand return to prematurely return from a stack
frame, thereby short-circuiting its execution.
Executing thread return 1 did the trick. This returned true (1) to the index out of range issue and then continued the execution to the next line of code.

Xcode 8 random command failed due to signal segmentation fault 11

I have a strange problem with the new Xcode 8 (no beta version) and swift3.
Once every other 3-4 times that I compile my code I get a 'command failed due to signal segmentation fault 11' error. I just need to enter new empty line, or sometimes changing some spaces, or add a comment (everywhere in the code) and the error disappears and I can compile again.
This is really strange because I'm not changing anything in the code! And sometimes I can compile and it works, then I don't change anything, I compile again and I get the error.
This is really annoying!
I have noticed this is happening since I have installed several 'Firebase' pods (Firebase, Firebase/Auth etc...). But I need them.
Anyone has any suggestion?
PS: I have set the Enable Bitcode of my project to No as many solution suggested, but nothing. In the error message it is not indicated any swift page where the error can be, an example is:
While loading members for 'Class_name' at
While deserializing 'func_name' (FuncDecl #42)
'func_name' is this one:
public class func loginUser(fir_user: FIRUser) {
let user = SFUser()
user.email = fir_user.email
user.isLogged = true
try! sfRealm.write() {
sfRealm.add(user, update:true)
}
var userToAdd = [String:AnyObject]()
userToAdd["email"] = fir_user.email! as NSString
let ref=FIRDatabase.database().reference()
let usersRef = ref.child(childName)
usersRef.setValue([key:value])
}
But then, as I said, I can just enter an empty row in another file and it compiles!
Thanks
I have the same issue i just figure out that i was using xcode 8.1 and the project's working copy was in xcode 8.2.1 so i just re install xcode 8.2.1 and problem got solved. Hope other can get the help trough this.
Ok, it seems that I have found the solution: it is a problem with Firebase and cocoapods, so 2 solutions:
Download Firebase and import into your project
I, instead, updated cocoapods to the last version and it worked. Upgraded Firebase - Now Getting Swift Compile Error
In my case there was some type checking issue deep down the compiler so the editor didn't give error in the gutter but on building the project I was getting signal setmentation fault 11 error:
1. While type-checking 'GetStoreAPIRequestModel' at /Users/.../StoreAPIModel.swift:9:1
2. While type-checking expression at [/Users/.../StoreAPIModel.swift:15:18 - line:15:31] RangeText="[Dictionary]()"
3. While resolving type [Dictionary] at [/Users/.../StoreAPIModel.swift:15:18 - line:15:29] RangeText="[Dictionary]"
So I changed my code from:
var stores = [Dictionary]() {
willSet {
allStores.removeAll()
for model in newValue {
allStores.append(StoreAPIModel(dictionary: model as! Dictionary).getModel())
}
}
}
To (more descriptive dictionary):
var stores = [[String : Any]]() {
willSet {
allStores.removeAll()
for model in newValue {
allStores.append(StoreAPIModel(dictionary: model as [String : AnyObject]).getModel())
}
}
}
This is tricky problem. Issue can be with line of code or syntax. I was getting similar error and it was due to incorrect usage of dictionary. I was trying to increment the value of dictionary element.
Solution is to triage the code, detailed error provide which module has issue, so try commenting part of code until you find the line which is causing the issue.
Hi i had the same issue with FireBase , my problem was that i was extending FIRStorageReference and FIRDatabaseReference and some time it compile successfully some time i get
command failed due to signal segmentation fault 11
so i removed that files and implement the method other way , now everything works fine.
Found my problem when this occurred. (No cocoapods.) I thought I had left the program in a working state, but I was wrong. I am writing a straightforward command-line program. What it does is somewhat general, so I defined all the strings that make it specific in let statements at the top of the program so that I could someday use the program in a different context.
Since that was working so well, I thought I'd be clever and do the same with a filter of an array of dictionaries. I turned:
list.filter { $0["SearchStrings"] == nil }
into:
let test = { $0["SearchStrings"] == nil }
// ...
list.filter(test)
meaning to continue working on the let, but I never went back and did that. Building gave me the segmentation fault error. Defining test as a function fixed the problem.
(Incidentally, I understand how to strip a filtering function down to the terse braces notation in the context of the call to Array.filter, and why that works, but I don't understand why I can't assign the brace expression to a constant and use it as such.)

Stanford Calculator app keeps crashing

I'm taking the Stanford iPad and iPhone developer course online at Stanford using Swift and working on creating a Calculator application. (Still a bit new to programming.)
However, it keeps crashing with the error message whenever I select an operator from the calculator.
operandStack = [36.0]
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
and then when I look in ViewController to see what part of the source code is highlighted. It is this:
NSNumberFormatter().numberFromString(display.text!)!.doubleValue }
the error message under this though, reads:
THREAD 1:EXC_BAD_INSTRUCTION(code:EXC_1386_INVOP,subcode=0x0)
I don't understand what's going on, since I entered the code, word for word from the lecture.
Any help is appreciated!
Thanks in advance!
I am stuck at that part of the course too!
I think that apple recently made changes to NSNumberFormatter's numberFromString method. Because when I printed out display.text!, there was nothing wrong. In other words, it does not found nil while unwrapping that part.
Another part we are unwrapping is here, at the second ! mark, we unwrap only this part:
NSNumberFormatter().numberFromString(display.text!)
But we have an error out of this, so numberFromString should be returning nil.
But in the videos, it doesn't. It perfectly turns floating point number strings (such as "36.0") to NSNumber, then to Double.
And since your question was asked on May 20th and I could not find any "old" questions, I think Apple had changed the code on numberFromString.
Edit: I did something crazy and used Find & Replace (command + F) to replace all "Double"s to "Int"s in my code. The multiplication part works well now, I think the problem is about the "." part on Doubles.
Edit 2: I solved it. Some countries such as US use "." to separate decimals and some others such as Turkey use "," to do it. It works on video because he's doing it on US.
NSNumberFormatter has a property called decimalSeparator. We have to set it to ".". I did the following changed to my code and it worked perfect.
var displayValue: Double {
get {
var formatter = NSNumberFormatter()
formatter.decimalSeparator = "."
return (formatter.numberFromString(display.text!)!.doubleValue)
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingNumber = false
}
}
"found nil while unwrapping an Optional" means that you have a variable that may or maynot have a value, when you use the operator ! you are telling swift "Trust me there is a value in there" however if there is not swift will throw a exception as the one you just saw.
The best way to avoid this is checking before use:
if let value = display.text{
//if your code get here value is safe to use
NSNumberFormatter().numberFromString(value).doubleValue
}

Index error when filling in an array with a randomly generated array

I am getting an error when running this bit of code about the index. I have ran through the logic several times and have yet to catch my error and I am thinking it is in the way I coded this section. Any help would be greatly appreciated. Please let me know if I am missing any information vital for this bit of code.
index_pairs = [1,12661;12662,46147;46148,52362]
group_class_count = [10137,2524;127448,20738;1570,4645]
group_count = 3
cross_sections = 10
for j=1:group_count
rand_index=randsample(index_pairs(j,1):index_pairs(j,2),(group_class_count(j,1)+group_class_count(j,2)),true); % Creates an index of random rows for the current group.
cross_size(j)=floor(size(rand_index,2)/cross_sections);
for k=1:cross_sections
cross_rand_indices(j,k)={rand_index(cross_size*(k-1)+1:cross_size*(k))};
end
end
error: Index exceeds matrix dimensions. Error in cross_rand_indices(j,k)={rand_index(cross_size*(k-1)+1:cross_size*(k))};
If you change
cross_rand_indices(j,k)={rand_index(cross_size*(k-1)+1:cross_size*(k))};
to
cross_rand_indices(j,k)={rand_index(cross_size(j)*(k-1)+1:cross_size(j)*(k))};
the error will disappear.
I assume this is in line with your intent when saving something to cross_size(j) in the outer loop.

getblast error unavilable matlab

I'm writing matlab code that's supposed to iterate over a list sequences and blast each at a time. Here is the relevant part of the code:
%blast the seq
[res, ROTE] = blastncbi(seq, 'blastn');
res1 = getblast(res, 'WaitTime',ROTE);
resName = res1.Hits(1).Name
for some seq's it worked, and then for the last it gave me this error message:
Error using getblast (line 176)
BLAST V7EBUE0901R is unavailable - try later.
please note that I've defined ROTE as the 'WaitTime' value, as suggested in the documentation of this function.
The script must iterate over lots and lots of genes, so I can't let it crash every 5 minutes!
The RTOE returned by blastncbi is an estimated time of how long it takes. Perhaps the estimate is sometimes simply incorrect.
Two simple ways to deal with this could be waiting longer, or trying it twice:
res1 = getblast(res, 'WaitTime',ROTE*10);
or
try
res1 = getblast(res, 'WaitTime',ROTE);
catch
res1 = getblast(res, 'WaitTime',ROTE);
end
Of course this assumes that you are sure that the info that you request is actually available.