Segmentation Fault Error

Discussion in 'iOS Development' started by TechnoEagle, Feb 5, 2010.

  1. TechnoEagle

    TechnoEagle Member

    Joined:
    Jan 2, 2010
    Messages:
    169
    Likes Received:
    0
    Device:
    4G iPod touch
    I am writing a program in Xcode, but when I run it, I get a "Segmentation fault" error. Here is the method that keeps giving me the error. I don't have much experience with memory management or Objective-C, so help would be appreciated!

    Please Register or Log in to view images


    Code:
    -(NSString *)description
    {
    	NSString *description=[[NSString alloc] init];
    	description=[NSString stringWithFormat:@"Hello! I am a %1.2f-sided (aka a %@) with angles of %1.2f (%1.2f radians)", numberOfSides, [self getName], [self getAngleInDegrees], [self getAngleInRadians]];
    	[description autorelease];
    	return description;
    }
    Thanks!

    Please Register or Log in to view images

  2. Axis

    Axis Super Moderator Staff Member

    Joined:
    Dec 2, 2007
    Messages:
    6,288
    Likes Received:
    133
    Device:
    iPhone 4S (White)
    The first line leaks, you allocate memory, then immediately reassign the pointer. The return value of +[stringWithFormat] is a pointer to an autoreleased object, so you can't (and don't need to) call -[release]/-[autorelease].

    That won't mean much until you actually learn obj-c memory management. There are plenty of resources available online, for free, including materials from Apple.

    There is a problem with the arguments you are passing (and/or the methods used to obtain them), but I'm not going to bother with that now.
  3. NolesFans

    NolesFans New Member

    Joined:
    Sep 23, 2008
    Messages:
    404
    Likes Received:
    0
    Device:
    iPod touch
    [objc]-(NSString *)description
    {
    return [NSString stringWithFormat

    Please Register or Log in to view images

    "Hello! I am a %1.2f-sided (aka a %@) with angles of %1.2f (%1.2f radians)", numberOfSides, [self getName], [self getAngleInDegrees], [self getAngleInRadians]];
    }[/objc]

    Please Register or Log in to view images

  4. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    A few things that Axis maybe implied:

    Why are you using a float placeholder for numberOfSides? The code should still work (due to automatic casting), but you should instead use %d or %u to specify an [unsigned] integer.

    In addition, -get(…) methods are (AFAIK, following naming conventions) only used if a value is being copied and has to be released by the sender, e.g. NSString's -getCString:length:usingEncoding:
    You should maybe rename those methods to name, angleInDegrees, etc.

Share This Page