Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - Command line (clang) - print Stack Trace

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
like image 915
user1046037 Avatar asked Dec 01 '25 21:12

user1046037


1 Answers

#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);
}
like image 78
rob mayoff Avatar answered Dec 03 '25 21:12

rob mayoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!