0

I'm a c-noob if it comes to strings hand converting back and forth from objective-c and c itself. I want to convert a string to a mp_int and back. The library i'm using is libtommath and the method signatures are below.

mp_int a;
mp_init(&a);

int res = mp_read_radix(&a, "3493483984238472398423742344793247923648234", 10);
NSLog(@"%i", res);

unsigned char *b = malloc(255);
mp_toradix(&a, &b, 10);

NSString *c = [[NSString alloc] initWithCString:b encoding:NSASCIIStringEncoding];

NSLog(@"--%@", c);

Method signatures:

int mp_init (mp_int * a)
int mp_read_radix (mp_int * a, const char *str, int radix)
int mp_toradix (mp_int * a, char *str, int radix)

The code above seems to be bonkers ... can anyone help? It gives a EXC_BAD_ACCESS at the end of the function call (close bracket).

Mark

Augunrik
  • 1,866
  • 1
  • 21
  • 28
  • possible duplicate of [How to convert from int to string in objective c: example code](http://stackoverflow.com/questions/1104815/how-to-convert-from-int-to-string-in-objective-c-example-code) – dirkgently Jun 11 '12 at 19:13
  • 1
    By the way, there are some nice conversion functions already available to you. Cstring -> int via atoi; ObjCstring -> int via [myString intValue]; backwards via sprintf or [NSString stringWithFormat:...]; and you can NSLog out a C string without having to first convert to an Obj-C string using NSLog(@"%s", cStr); – Tyler Jun 11 '12 at 20:24
  • The problem is, that I have to provide a pointer to the function and it doesn't return one... :/ – Augunrik Jun 12 '12 at 17:42

1 Answers1

2

mp_toradix(&a, &b, 10); is wrong. It should be mp_toradix(&a, b, 10);


As side notes, you're leaking the memory allocated to b.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117