3

Need to generated some random 10 byte length string in c function and call the function from objective-c. So, I'm creating a pointer to uint8_t and passing it to C function. The function generates random bytes and assigns them to *randomString. However, after returning from function to objective-c randomValue pointer points to NULL.

Here's my random function in C:

void randomString(uint8_t *randomString)
{
  randomString = malloc(10);

  char randomByte;
  char i;
  for (i = 0; i < 10; i++) {

    srand((unsigned)time(NULL));
    randomByte = (rand() % 255 ) + 1;
    *randomString = randomByte;
    randomString++; 
  }
} 

Here's objective-c part:

uint8_t *randomValue = NULL;
randomString(randomValue); //randomValue points to 0x000000

NSString *randomString = [[NSString alloc] initWithBytes:randomValue length:10 encoding:NSASCIIStringEncoding];
NSLog(@"Random string: %@", randomString);

3 Answers 3

3

A more natural semantic, like malloc() itself would be:

uint8_t * randomString()
{
    uint8_t *randomString = malloc(10);
    srand((unsigned)time(NULL));
    for (unsigned i = 0; i < 10; i++)
        randomString[i] = (rand() % 254) + 1;
    return randomString;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This also works and reads better uint8_t *randomValue = randomString();
2

Pointers are passed by value, so randomValue will remain NULL after the call of randomString. You need to pass a pointer to a pointer in order to make it work:

void randomString(uint8_t **randomString) {
    *randomString = malloc(10);
    // ... the rest of your code goes here, with an extra level of indirection
}

uint8_t *randomValue = NULL;
randomString(&randomValue);

1 Comment

exactly what I was thinking! :)
1

You probably should be using uint8_t **randomeValue instead of uint8_t *.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.