简体   繁体   中英

Reallocating **array

My 2d array char **buffer is being created. The malloc part works. The realloc part is generating a segmentation error.

These are the 2 functions which do the following;

//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");
}
}

I guess buf_x is global.
You will need to store the original size and pass it to the function.
If elements are added, the new elements need to be set to NULL so realloc will succeed.

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

check if realloc fails

//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]);
        }
    }
}

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