lifewithelliott
lifewithelliott

Reputation: 1432

How to allocate memory to a string array in C - malloc error

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;
}

enter image description here enter image description here enter image description here

Upvotes: 0

Views: 305

Answers (1)

AdminXVII
AdminXVII

Reputation: 1329

You did not take into account the fact that the size of a pointer is not one. Hence, only a fraction of the size was allocated. Thus, some pointers had not enough memory to be allocated, causing the program to crash only when accessing one of those.

#define PACKAGE_COUNT 60
#define MAX_COUNT     5

const char *colors[] = { "blue", "red", "yellow", "purple", "orange" };

char **generatePackage() {
  char **generatedPackage = malloc(PACKAGE_COUNT * sizeof(char*)); // The size of a pointer is not one, so this a multiplicative factor must be applied
  int randomIndex         = 0;

  for (int i = 0; i < PACKAGE_COUNT; ++i) { // the upper bound is i < PACKAGE_COUNT, not i <= PACKAGE_COUNT

    randomIndex         = rand() / (RAND_MAX / MAX_COUNT + 1);
    generatedPackage[i] = malloc(sizeof(char) * (strlen(colors[randomIndex]) + 1)); // You probably want to allocate enough space for the string, rather than enough space for the pointer, so you must use strlen

    strcpy((generatedPackage[i]), colors[randomIndex]);

    // printf("generatePackage - %d: %s \n", i + 1, generatedPackage[i]);
  }

  return generatedPackage;
}

Upvotes: 5

Related Questions