简体   繁体   中英

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

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM