【问题标题】:create two dim array of char with malloc in C在 C 中使用 malloc 创建两个暗淡的 char 数组
【发布时间】:2018-12-30 19:49:53
【问题描述】:

我用 malloc 创建了以下两个暗淡的 char 数组,称为 json_data。 mem进程的分配工作正常。

char **json_data;
json_data = (char**)malloc(sizeof(char *) * NUMBER_OF_OBJECT);
for (int i = 0; i < NUMBER_OF_OBJECT; i++) {
    *(json_data + i) = (char*)malloc(sizeof(char) * 10000);
}

但每当我尝试访问数据时,都会收到 SegmentationFault 错误。 以下是我用来访问json_data中数据的方法:

第一个:

    for (int i = 0; i < NUMBER_OF_OBJECT; i++ ) {
        for (int j = 0 ; j < 10000; j++ ) {
            printf("%c", *(*(json_data +i) + j));
        }
    }

第二个:

    for (int i = 0; i < NUMBER_OF_OBJECT; i++ ) {
        for (int j = 0 ; j < 10000; j++ ) {
            printf("%c", json_data[i][j]);
        }
    }

这是完整的代码,直到 foo 循环:

    // define local variables
int CHAR_SIZE = size_in_char("main.json"); // size of file in bytes, each char represents a byte
int NUMBER_OF_OBJECT = 0; // number of object in json file


// array holding json data char by char
char *data = malloc( sizeof(char)* CHAR_SIZE );
store("main.json", data);

char **json_data;
json_data = (char**)malloc(sizeof(char *) * NUMBER_OF_OBJECT);
for (int i = 0; i < NUMBER_OF_OBJECT; i++) {
    *(json_data + i) = (char*)malloc(sizeof(char) * 10000);
}


int j = 0; // index of data array
int bracket_counter = 0; // conter for  opning and closing of json object
int obj_index = 0; // index of json_data array

while( data[j] != '\0') {

    // start & end of an object
    // k temporay index for each object
    int k = 0, start = 0 , end = 0;

    if ( data[j] == '{') {

        if (bracket_counter == 0 ) {
            // begining of json object
            start = j; // stroe the value of begining
            bracket_counter++;
            k = j; // init the temp index

            do {
                // keep going until the end of json object
                k++;
                if (data[k] == '{') {
                    bracket_counter++;
                }
                if ( data[k] == '}') {
                    bracket_counter--;
                }
            } while (/*data[k] != '}' &&*/ bracket_counter != 0);
            end = k; // store end of json object

            // copy copy json object into json_data
            strncpy(json_data + obj_index, data + start , end - start + 2 );
            *(json_data + obj_index + ( end - start + 1 ) ) = '\0'; // add null terminated value at end
            obj_index++;

        }

        j = k; // move data index to end of current object and contineu the parsing
    }
    j++;
}


printf("the json file contains %d objects\n", NUMBER_OF_OBJECT);

for (int i = 0; i < NUMBER_OF_OBJECT; i++ ) {
    for (int j = 0 ; j < 10000; j++ ) {
        printf("%c", json_data[i][j]);
    }
}


void store(string filename, char *data) {
/*
open file named by filename.
read data and stored it in data[].
data[] need to be created and memory allocated in main function
*/

char buff = 1; // buffer for fgetc();
int j = 0 ; // index of array data[];

FILE *file = fopen(filename, "r");
if (!file) {
    printf("ERROR OPENING FILE\n");
    printf("press enter to exit...");
    getc(stdin);
    exit(cant_open_file);
}

while ( buff  != EOF) {
    // read char by char
    buff = fgetc(file);

    // escape whitespace char during the process
    if ( buff != '\n' && buff != ' ' && buff != '\t') {
        data[j++] = buff;
    }
}

// add null terminated value at end of array
data[j] = '\0';

// close the file
fclose(file);

}

【问题讨论】:

  • 什么是NUMBER_OF_OBJECT
  • 只是int类型的数字
  • 它的定义是什么? 1? 10? 1000?在 for 循环中使用它很重要
  • json_data 是一个由 NUMBER_OF_OBJECT 个 json 对象组成的数组,每个对象的最大大小为 10000 个字符

标签: c arrays malloc


【解决方案1】:

它崩溃了,因为你的 for 循环通过的元素比你分配的要多:

*(json_data + i) = (char*)malloc(sizeof(char) * 10000);

一万

for (int j = 0 ; j < 100000; j++ ) {

十万

【讨论】:

  • 对不起那个错误我需要更新问题,我对分配和 for 循环都使用了相同的长度 10000,但我仍然得到相同的错误
  • @ablil98 当我修复它并重新编译时,它不再对我来说是段错误了。那么问题必须出在您没有发布的程序的一部分。请在您的问题中编辑一个显示问题的完整程序,无需添加或修改即可编译。
  • 我更新问题,你可以看看完整的programm直到foor循环
  • @ablil98 这还不是一个完整的程序。它缺少 #includes 和 main 声明之类的东西。我应该能够编译和测试您的代码,而无需自己添加任何内容。
  • 完整代码:link,相关文件在同一个repo中
【解决方案2】:

“崩溃”的最可能原因是 - 取决于 NUMBER_OF_OBJECT 的值 - 在某些时候系统不再分配内存。 在分配更大的内存块时,尤其是在循环中执行此操作时,请始终检查malloc 的结果;如果是NULL,则系统无法保留你申请的内存:

char **json_data;
json_data = (char**)malloc(sizeof(char *) * NUMBER_OF_OBJECT);
if (json_data == NULL) {
   printf("could not allocate memory.");
   exit(1);
}
for (int i = 0; i < NUMBER_OF_OBJECT; i++) {
   char* obj = (char*)malloc(sizeof(char) * 10000);
   if (obj == NULL) {
      printf("could not allocate memory.");
      exit(1); 
   }
   *(json_data + i) = obj;
}

返回NULLmalloc 不会导致未定义的行为;但如果没有这些检查,您可能会将NULL 分配给稍后取消引用的元素之一。然后这将是 UB,可能是段错误崩溃。

顺便说一句:请注意,您只是分配内存,而不是初始化它。据我所知,这是未定义的行为;可能您没有显示您填写内容的代码;否则,使用calloc(而不是malloc)至少会将内存块初始化为0

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 2019-10-08
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多