0

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");
}
}
lfarr
  • 17
  • 6
  • but how can I change the size of the buffer, and at the same time not removing the elements within it? or should i save the elements in the array and then put them back in the reallocated one? thank you – lfarr May 09 '17 at 16:23
  • @xing i have modified the code. can you check whether ive followed your advice please. thank you – lfarr May 09 '17 at 16:29
  • 1
    That`s a jagged array, not a 2D array! Completely different datatype! – too honest for this site May 09 '17 at 16:29
  • @xing so the should i just set buffer[0] = NULL at the beginning of the function adjustBuffer? thanks – lfarr May 09 '17 at 16:33
  • [don't cast the result of `malloc` in C](http://stackoverflow.com/q/605845/995714) – phuclv May 09 '17 at 16:59
  • A *pointer to pointer to char* is not an *array of arrays of type char*. Always `realloc` with a `tmp` pointer and not the actual variable. If `realloc` fails, you lose your reference to the original block of memory. – David C. Rankin May 09 '17 at 17:26

1 Answers1

0

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]);
        }
    }
}
xing
  • 2,125
  • 2
  • 14
  • 10