3

I would like to print the stack trace for my Objective-C program

I am compiling from the command line using clang (Automatic reference counting)

I would like to know the following:

  1. Do I have to add any parameters while compiling ?
  2. Do I have to add any code to start the trace and print the trace ?

Given below is a sample program for which I have to print the stack trace:

#import<Foundation/Foundation.h>

@interface Car : NSObject
@property (weak) NSNumber* doors;
@end

@implementation Car 
@synthesize doors;
@end

int main()
{
    system("clear");

    Car *car1 = [[Car alloc] init];

    NSNumber *d1 = [[NSNumber alloc] initWithInteger: 4]; 

    //I want to start printing the stack trace from this point on
    car1.doors = d1;

    printf("---- end\n");

    return(0);
}

Command used to compile:

clang -fobjc-arc test.m -framework Foundation -o test
user1046037
  • 16,755
  • 12
  • 92
  • 138

1 Answers1

2
#include <execinfo.h>

void printStackTrace() {
    void *returnAddresses[500];
    int depth = backtrace(returnAddresses, sizeof returnAddresses / sizeof *returnAddresses);
    printf("stack depth = %d\n", depth);
    char **symbols = backtrace_symbols(returnAddresses, depth);
    for (int i = 0; i < depth; ++i) {
        printf("%s\n", symbols[i]);
    }
    free(symbols);
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks, I have a doubt, in the program I had pasted earlier when the statement `car1.doors = d1;` is executed a segmentation fault occurs, so how do I get to know what causes the segmentation fault. If invoke the function `printStackTrace()` before the statement that causes the segmentation fault the trace doesn't show much, if i invoke after the statement that causes the segmentation fault, it doesn't reach there. – user1046037 Nov 15 '11 at 08:07
  • 1
    I suppose there is more than 1 way to do it, given below is the link which shows an option to do it: http://stackoverflow.com/questions/8125530/objective-c-arc-nsnumber-segmentation-fault – user1046037 Nov 15 '11 at 08:21