0

I'm really new to Objective C and am trying to write a program to go through the collatz conjecture. When I run the program, it stops after the first scanf and comes up with "EXC_BAD_ACCESS". Here's my code:

int original,i;

NSString *PrintFull;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSLog(@"Collatz Conjecture:");
    NSLog(@"Print full results?");
    scanf("%s",PrintFull);

    NSLog(@"What number should we go up to?");
    scanf("%d", &original);

    while (original <= 100) {
        NSLog(@"\n\n%d", original);
        i = original;
        while (i != 1) {
            if (i % 2) {
                i = (i*3)+1;
            } else {
                i = (i/2);
            }

            if ([PrintFull isEqualToString:@"yes"]) {
                NSLog(@"%d",i);
            }
        }

        original++;
    }
}

What am I doing wrong here?

Jason Coco
  • 77,985
  • 20
  • 184
  • 180

3 Answers3

2

scanf does not work with with object types such as NSString. Please see SO post - Using scanf with NSStrings.

Community
  • 1
  • 1
5StringRyan
  • 3,604
  • 5
  • 46
  • 69
2
  • scanf's arguments after the format string should point to already allocated objects. In this case you've just declared a pointer and passed it in without setting it. scanf will try to write to this location, but since the pointer contains a garbage value, the application crashes.

  • scanf is from the C library 'stdio.h', meaning it doesn't know about NSStrings, which are from the Objective-C 'Foundation' framework.

The following should solve these problems

int original,i;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSLog(@"Collatz Conjecture:");

    NSLog(@"Print full results?");

    char inputBuffer[80];
    scanf("%s", inputBuffer);
    NSString *printFull = [NSString stringWithCString:inputBuffer encoding:NSUTF8Encoding];
joerick
  • 16,078
  • 4
  • 53
  • 57
  • It's actually still possible to crash here by typing more than 80 characters. Using `scanf("%80s", inputBuffer);` would prevent this. – joerick Dec 28 '11 at 16:30
1

First, you have to initialize and alloc the NSString. Second, scanf can't handle NSString.

Also notice, that class names begin with a capital letter and class instances with a small one.

tamasgal
  • 24,826
  • 18
  • 96
  • 135