0

I understand that this error has to do with how much memory my program tries to use when I run it, but I'm new to C and I don't quite have a handle on memory management yet. If anyone wants to take the time to tell me where in my code this is occurring I would very much appreciate it.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

char * getRandomHex(int length, char * result) {
    char hexCharacters[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    
    for (int i = 0; i < length; i++) {
        char randChar = hexCharacters[rand()%16];
        strncat(result, &randChar, 1);
    }

    return result;
}

int main() {
    for (int i = 0; i < 10; i++) {
        char * result;
        result = getRandomHex(6, result);
        printf("%s", result);
        printf("\n");
    }
}
Riley391
  • 3
  • 1

1 Answers1

1

The first 3 of these are the main issues:

  1. main(): allocate space for result.
  2. getRandomHex() assign to result[i] instead of using strncat() incorrectly.
  3. getRandomHex(): don't assume that result argument contains a terminating '\0'.
  4. getRandomHex() using a string as it's easier to write. Making it static const as it read-only.
  5. Removed unused headers.
  6. Define LEN instead of the magic number 6.
  7. Derived size of hexCharacters() instead of hard-coding it to 16.
  8. Combine the two print statements, and using the return value (which is the result variable).
#include <stdio.h>
#include <stdlib.h>

#define LEN 6

// caller must allocate result array of size at least length + 1 bytes
char *getRandomHex(int length, char *result) {
    static const char hexCharacters[] = "0123456789ABCDEF";
    for (int i = 0; i < length; i++) {
        result[i] = hexCharacters[rand() % (sizeof(hexCharacters) - 1)];
    }
    result[length] = '\0';
    return result;
}

int main() {
    char result[LEN + 1];
    for (int i = 0; i < 10; i++) {
        printf("%s\n", getRandomHex(LEN, result));
    }
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • You will *probably* want to seed your pRNG, unless the deterministic nature of the current output is desired (see: [`srand`](https://en.cppreference.com/w/c/numeric/random/srand)). The cursory `` was likely included as a preamble to the [usual simplistic way of creating a seed](https://stackoverflow.com/a/822368/2505965). – Oka May 19 '22 at 04:59
  • @Oka good comment, thanks. It is not clear if op wants the current or proposed changed behavior. – Allan Wind May 19 '22 at 05:01