重新分配**数组

时间:2017-05-09 16:18:19

标签: c arrays malloc realloc

正在创建我的2d数组char **缓冲区。 malloc部分有效。 realloc部分正在生成分段错误。

以下是执行以下操作的2个功能;

//sets up the array initially
void setBuffer(){
buffer = (char**)malloc(sizeof(char*)*buf_x);

for(int x=0;x<buf_x;x++){
    buffer[x] = (char *)malloc(sizeof(char)*buf_y);
}

if(buffer==NULL){
    perror("\nError: Failed to allocate memory");
}
}

//changes size
//variable buf_x has been modified
void adjustBuffer(){
for(int x=prev_x; x<buf_x;x++) {
    buffer[x] = NULL;
}

buffer=(char**)realloc(buffer,sizeof(char*)*buf_x);

for(int x=0; x<buf_x;x++){
    buffer[x]  = (char*)realloc(buffer[x],sizeof(char)*buf_y);
    strcpy(buffer[x],output_buffer[x]);
}
if(buffer == NULL){
    perror("\nError: Failed to adjust memory");
}
}

1 个答案:

答案 0 :(得分:0)

我猜buf_x是全球性的 您需要存储原始大小并将其传递给该功能 如果添加了元素,则需要将新元素设置为NULL,以便realloc成功。

//variable buf_x has been modified
void adjustBuffer( int original){
    buffer=realloc(buffer,sizeof(char*)*buf_x);
    for(int x=original; x<buf_x;x++){
        buffer[x] = NULL;//set new pointers to NULL
    }
    for(int x=0; x<buf_x;x++){
        buffer[x]  = realloc(buffer[x],sizeof(char)*buf_y);
    }
}

检查realloc是否失败

//variable buf_x has been modified
void adjustBuffer( int original){
    if ( ( buffer = realloc ( buffer, sizeof(char*) * buf_x)) != NULL) {
        for ( int x = original; x < buf_x; x++) {
            buffer[x] = NULL;//set new pointers to NULL
        }
        for ( int x = 0; x < buf_x; x++){
            if ( ( buffer[x] = realloc ( buffer[x], strlen ( output_buffer[x]) + 1)) == NULL) {
                break;
            }
            strcpy(buffer[x],output_buffer[x]);
        }
    }
}