XMAX
XMAX

Reputation: 29

Why am I getting buffer overflow?

In the below code I am getting AddressSanitizer : Heap-Buffer-Overflow. I am trying to generate Pascal`s triangle. When i run this code in visual studio 2022 , the code runs perfectly without producing errors.

 int** generate(int numRows, int* returnSize, int** returnColumnSizes){
    int** ptr = (int**)malloc(numRows*sizeof(int*));
    *returnColumnSizes = (int*)malloc(numRows*sizeof(int)); 
    *returnSize = numRows; 
    for (int r = 0; r < numRows; r++) {
        ptr[r] = (int*)malloc(r+1*sizeof(int));
        returnColumnSizes[0][r] = r+1;
    }
    if (numRows == 1) {
        ptr[0][0] = 1;
    }
    else {
        ptr[0][0] = 1;
        ptr[1][0] = 1;
        ptr[1][1] = 1;
        for (int r = 2; r < numRows; r++) {
            for (int c = 0; c < r + 1; c++) {
                if (c == 0) {
                    ptr[r][c] = 1;
                }
                else {
                    ptr[r][c] = ptr[r - 1][c - 1] + ptr[r - 1][c];
                }
            }
            ptr[r][r] = 1;
        }
    }
    return ptr;

  
}

Upvotes: 0

Views: 77

Answers (1)

BSO_1
BSO_1

Reputation: 64

Buffer overflow simply means you are trying to access memory in the heap that you have not allocated yet. So you should check memory allocation in your code to ensure you allocate enough memory. The starting point would be to check if the following line

ptr[r] = (int*)malloc(r+1*sizeof(int));

does allocate enough memory for you to run the loop

else {
        ptr[0][0] = 1;
        ptr[1][0] = 1;
        ptr[1][1] = 1;
        for (int r = 2; r < numRows; r++) {
            for (int c = 0; c < r + 1; c++) {
                if (c == 0) {
                    ptr[r][c] = 1;
                }
                else {
                    ptr[r][c] = ptr[r - 1][c - 1] + ptr[r - 1][c];
                }
            }
            ptr[r][r] = 1;
        }
    }
 

You should assign enough memory for the number of rows with each run of the

ptr[r] = (int*)malloc(r+1*sizeof(int));

Upvotes: 1

Related Questions