Can you tell me where the buffer overflow is coming from?

Asked 2 years ago, Updated 2 years ago, 24 views

#include <iostream>
#include <stdio.h>
#include <string.h>

// // codeup NO.1098
using namespace std;

int main()
{
    int h = 0, w = 0;
    scanf("%d %d", &h, &w);
    int** b = new int* [h + 1];
    for (int i = 0; i < h + 1; i++)
    {
        b[i] = new int[w + 1];
        memset(b[i], 0, sizeof(int) * (h + 1));

    }

    /*
    for (int i = 1; i < h + 1; i++)
    {
        for (int j = 1; j < w + 1; j++)
        {
            printf("%d ", b[i][j]);
        }
        printf("\n");
    }
    */


    int n = 0; // Variable to determine how many bars to put
    scanf("%d", &n);

    while (n > 0)
    {
        int L = 0, d = 0, x = 0, y = 0;
        scanf("%d %d %d %d", &L, &d, &x, &y);
        if (d == 0)
        {
            for (int i = 1; i <= L; i++)
            {
                b[x][y] = 1;
                y++;
            }

        }
        else if (d == 1)
        {
            for (int i = 1; i <= L; i++)
            {
                b[x][y] = 1;
                x++;
            }

        }
        n--;
    }

    for (int i = 1; i < h+1; i++)
    {
        for (int j = 1; j < w+1; j++)
        {
            printf("%d ", b[i][j]);
        }
        printf("\n");
    }

    for (int i = 0; i < h + 1; i++)
    {
        delete[] b[i];

    }
    delete[] b;


    return 0;
}

It works well in the visual studio, but it doesn't work when I put it in the code-up ㅇㅅㅇ...

Main: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

c++

2022-09-22 16:46

1 Answers

I haven't read all the codes, but I think the error contents are related to memset, so I looked around.

If it's w + 1 < h + 1, I think it's right to get caught by Assertion

You did new int [w + 1], but since you initialized h + 1, I think it's going to go over the array area.


2022-09-22 16:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.