Problem: I want to allocate memory to the elements of a fixed sized string array, however, I experience a crash 75% of the time.
That is 25% of the time my program runs flawlessly, but the error is one I have not experienced before
#define PACKAGE_COUNT 60
#define MAX_COUNT 5
const char *colors[] = { "blue", "red", "yellow", "purple", "orange" };
char **generatePackage() {
char **generatedPackage = malloc(PACKAGE_COUNT);
int randomIndex = 0;
for (int i = 0; i <= PACKAGE_COUNT; ++i) {
randomIndex = rand() / (RAND_MAX / MAX_COUNT + 1);
generatedPackage[i] = malloc(sizeof(char) * sizeof(colors[randomIndex]));
// ERROR
strcpy((generatedPackage[i]), colors[randomIndex]);
// printf("generatePackage - %d: %s \n", i + 1, generatedPackage[i]);
}
return generatedPackage;
}



malloc(sizeof(char) * sizeof(colors[randomIndex]))should bemalloc(strlen(colors[randomIndex]) + 1). Additionally, you need to allocate space for the pointers, as @xing points out