简体   繁体   English

二维char数组的malloc函数的分段错误

[英]Segmentation fault for malloc function of a 2D char array

Here is my code snippet to create the 2D array that holds char array. 这是我的代码段,用于创建保存char数组的2D数组。 It would be great if someone could find out what could be the reason. 如果有人能够找出原因,那将是很好的。 I have tried using both malloc() and calloc() to allocate memory to the 2D array, yet no positive signs. 我试过同时使用malloc()calloc()将内存分配给2D数组,但没有正号。

Code Snippet: 代码段:

char** attrNames = (char **)malloc(3*sizeof(char*))
for (m = 0; m < 3; m++) {
        attrNames[m] = (char *)malloc(2 * sizeof(char*));
        strcpy(schema->attrNames[m], temp_buff2[m]);
    }

I am trying to allocate the memory and then going on a loop and again allocating memory and copy the data from a variable called temp_buff2 (has character data) into the char array. 我试图分配内存,然后进行循环,再次分配内存,然后将数据从名为temp_buff2的变量(具有字符数据)复制到char数组中。

Try the code below. 试试下面的代码。 Even though memory allocation error in your project might be unlikely, now is a good time to develop a good error handling reflex - it will save your bacon when you move on to more serious projects. 即使您的项目中不太可能发生内存分配错误,但现在还是开发良好的错误处理反射的好时机-当您继续进行更认真的项目时,它将节省您的培根。

Note that char* pointer needs a buffer that is equal to the length of the string plus one extra byte. 请注意,char *指针需要一个缓冲区,该缓冲区等于字符串的长度加上一个额外的字节。 sizeof(char*) is a small value, only 8 on a 64-bit architecture - it just stores the value of the memory address where the string starts. sizeof(char *)是一个很小的值,在64位体系结构上只有8-它只是存储字符串开始处的内存地址的值。 Note that we need +1 on top of strlen() because strcpy() will store one extra byte (\\0) as a string terminator. 请注意,我们需要在strlen()顶部加上+1,因为strcpy()将存储一个额外的字节(\\ 0)作为字符串终止符。

char** attrNames = (char **)malloc(3*sizeof(char*));

if (!attrName)
{
  // handle memory error
}

for (m = 0; m < 3; m++) {
        attrNames[m] = (char *)malloc(strlen(temp_buff2[m])+1);
        if (!attrNames[m]) 
        {
           // handle memory error
        }

        strcpy(schema->attrNames[m], temp_buff2[m]);
    }

Memory error can be handled by returning an error code from your function or via a fatal exit like this: 可以通过从函数中返回错误代码或通过致命退出来处理内存错误,如下所示:

fprintf(stderr, "Out of memory\n");
exit(1);

You will need to #include <stdlib.h> for the prototype of exit(). 您需要#include <stdlib.h>以获得exit()的原型。

You need to reserve enough space for whatever you have inside "temp_buff2". 您需要为“ temp_buff2”中的内容保留足够的空间。 For example: 例如:

char** attrNames = (char **)malloc(3*sizeof(char*))
for (m = 0; m < 3; m++) {
    attrNames[m] = (char *)malloc( strlen(temp_buff2[m]) + 1 );
    strcpy(schema->attrNames[m], temp_buff2[m]);
}

Notice that I am adding 1 to the strlen result, this is because we need to reserve an additional byte for the null char terminator. 请注意,我在strlen结果中添加了1,这是因为我们需要为null char终止符保留一个额外的字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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