2

I have written a small Objective-C program to archive an object. The object is an NSDictionary. There was no problem during compiling. But when it was called it displayed a message "Segmentation fault" in the terminal, and no archive XML file was created. The problem was caused by the writeToFile method, as after I had commented it out there was no error (of course no archiving either). What does this error message mean? And how to fix it?

I just found out the reason of the problem. My program is based on the example in a book and there is a misprint so the dictionary object has never actually initialized. Sorry I did not check this problem throughly before asking.

God_of_Thunder
  • 753
  • 3
  • 20
  • 46
  • You have to show some code so someone can diagnose it. –  Jul 23 '12 at 12:56
  • In general, a segfault caused by bad memory access, but normally you'd get a bad access error in objective-c. Post your `writeToFile` method and any relevant code - I'm not clairvoyant and neither is anyone else on SO (aside from jon skeet). – Dustin Jul 23 '12 at 12:59

3 Answers3

2

A segmentation fault is caused by an attempt to dereference bad pointer. It's possible the file instance you're passing to writeToFile: is nil. You need to check your return codes for success, and check your pointers are all valid.

Given it does not crash when you comment out that line, you just need to ensure all the parameters to that call are valid and you will find your bug.

Some more reading:

Community
  • 1
  • 1
gavinb
  • 19,278
  • 3
  • 45
  • 60
2

Segmentation fault usually means that your program is accessing memory it shouldn't. Run your program in a debugger, and it should show you where the error happen.

fbafelipe
  • 4,862
  • 2
  • 25
  • 40
1

It's hard to pinpoint the exact problem without any sample code, but a segmentation fault occurs when the CPU is trying to access memory that it does not own. This generally means that you have a pointer that is not initialized, or doesn't point to the right place, and then you're attempting to de-reference it which causes the crash. I suggest combing over your code and make sure all your pointers are doing what you expect them to do.

Lanaru
  • 9,421
  • 7
  • 38
  • 64