admin管理员组

文章数量:1122832

I am dynamically allocating a 2D array based on user input for the number of rows and columns, but I encounter a memory access violation when trying to assign values to the maze[i] in the code. Here's the relevant part of my code.Could anyone help me?

I dynamically allocated memory for a 2D array in C

int main() {

    int m, n;
    
    scanf("%d%d", &m, &n);
    

    int** maze = (int**)malloc(sizeof(int*) * (m + 2));
    for (int i = 0; i < m + 2; i++) {
        maze[i] = (int*)malloc(sizeof(int) * (n + 2));
    }
    for (int i = 0; i < m + 2; i++) {
        for (int j = 0; j < n + 2; j++) {
            if (i == 0 || i == m + 1 || j == 0 || j == n + 1)maze[i][j] = 1;//1代表障碍
            else {
                if (j == n)scanf("%d\n", &maze[i][j]);
                else scanf("%d", &maze[i][j]);
            }
        }
    }
    for (int i = 0; i < m + 2; i++) {
        for (int j = 0; j < n + 2; j++) {
            
                if (j == n)printf("%d\n", maze[i][j]);
                else printf("%d ", maze[i][j]);
            
        }
    }
}

I am dynamically allocating a 2D array based on user input for the number of rows and columns, but I encounter a memory access violation when trying to assign values to the maze[i] in the code. Here's the relevant part of my code.Could anyone help me?

I dynamically allocated memory for a 2D array in C

int main() {

    int m, n;
    
    scanf("%d%d", &m, &n);
    

    int** maze = (int**)malloc(sizeof(int*) * (m + 2));
    for (int i = 0; i < m + 2; i++) {
        maze[i] = (int*)malloc(sizeof(int) * (n + 2));
    }
    for (int i = 0; i < m + 2; i++) {
        for (int j = 0; j < n + 2; j++) {
            if (i == 0 || i == m + 1 || j == 0 || j == n + 1)maze[i][j] = 1;//1代表障碍
            else {
                if (j == n)scanf("%d\n", &maze[i][j]);
                else scanf("%d", &maze[i][j]);
            }
        }
    }
    for (int i = 0; i < m + 2; i++) {
        for (int j = 0; j < n + 2; j++) {
            
                if (j == n)printf("%d\n", maze[i][j]);
                else printf("%d ", maze[i][j]);
            
        }
    }
}
Share Improve this question asked Nov 22, 2024 at 12:44 Louis SunLouis Sun 31 silver badge3 bronze badges 6
  • At which line does it crash according to your debugger and what are the values of m,n,i,j at that point? – Lundin Commented Nov 22, 2024 at 12:46
  • It is not an 2D array only an array of pointers. – 0___________ Commented Nov 22, 2024 at 12:48
  • Using a trailing white-space like "%d\n" as a format string for scanf is usually not doing what you expect, and is almost never needed. You don't need that if (j == n) check. – Some programmer dude Commented Nov 22, 2024 at 12:48
  • @Lundin:THanks for your reply! This question's setting is how to find a way out of a maze. And m,n,i,j stand for the maze matrix 's rows ,columns. I've edit this twice according a kind bro 's advice, in a bid to make it convenient to read, which results in the loss of the previous photo that emcompass the crash line information. l could say it's line6 :maze[i] = (int*)malloc(sizeof(int) * (n + 2)). – Louis Sun Commented Nov 22, 2024 at 13:08
  • @ 0___________: YES bro, but my visual studio seems not to support VLA when l encode:int (*maze) [m][n]. So l have to use function malloc to realize it. – Louis Sun Commented Nov 22, 2024 at 13:11
 |  Show 1 more comment

1 Answer 1

Reset to default 1
  1. Always check the result of malloc
  2. Always check the result of scanf
  3. Use meaningful variable names. Avoid n,m,i,j
  4. Use printfs or assertions when you try to debug your code.
  5. Use objects, not types in sizeof
  6. Comment your code.
  7. Clean all the rubbish behind (use free)
  8. Generally - do not be lazy when programming
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main()
{
    int totalRows, totalCols;
    int** maze = NULL; // Pointer to the maze
    int exitCode = EXIT_SUCCESS; // Single exit point
    int row;

    // Prompt user for the size of the maze
    printf("Enter the number of rows and columns: ");
    if (scanf("%d,%d", &totalRows, &totalCols) != 2)
    {
        fprintf(stderr, "Error: Invalid input for rows and columns.\n");
        exitCode = EXIT_FAILURE;
        goto cleanup;
    }

    // Allocate memory for the maze (array of row pointers) using calloc
    maze = calloc(totalRows + 2, sizeof(*maze));
    if (maze == NULL)
    {
        fprintf(stderr, "Error: Failed to allocate memory for maze rows.\n");
        exitCode = EXIT_FAILURE;
        goto cleanup;
    }

    // Allocate memory for each row
    for (row = 0; row < totalRows + 2; row++)
    {
        maze[row] = malloc(sizeof(*maze[row]) * (totalCols + 2));
        if (maze[row] == NULL)
        {
            fprintf(stderr, "Error: Failed to allocate memory for maze columns at row %d.\n", row);
            exitCode = EXIT_FAILURE;
            goto cleanup;
        }
    }

    // Input maze data
    printf("Enter the maze data (without boundaries, row by row):\n");
    for (row = 0; row < totalRows + 2; row++)
    {
        for (int col = 0; col < totalCols + 2; col++)
        {
            // Set boundary cells
            if (row == 0 || row == totalRows + 2 - 1 || col == 0 || col == totalCols + 2 - 1)
            {
                maze[row][col] = 1; // 1 represents a barrier
            }
            else
            {
                // Validate access within non-boundary regions
                assert(row > 0 && row <= totalRows);
                assert(col > 0 && col <= totalCols);

                // Read input for non-boundary cells
                if (col == totalCols)
                {
                    if (scanf("%d", &maze[row][col]) != 1)
                    {
                        fprintf(stderr, "Error: Invalid input for maze cell at row %d, col %d.\n", row, col);
                        exitCode = EXIT_FAILURE;
                        goto cleanup;
                    }
                }
                else
                {
                    if (scanf("%d", &maze[row][col]) != 1)
                    {
                        fprintf(stderr, "Error: Invalid input for maze cell at row %d, col %d.\n", row, col);
                        exitCode = EXIT_FAILURE;
                        goto cleanup;
                    }
                }
            }
        }
    }

    // Print the maze layout
    printf("Maze layout with boundaries:\n");
    for (row = 0; row < totalRows + 2; row++)
    {
        for (int col = 0; col < totalCols + 2; col++)
        {
            // Validate access within extended boundaries
            assert(row >= 0 && row < totalRows + 2);
            assert(col >= 0 && col < totalCols + 2);

            // Print maze layout
            if (col == totalCols + 2 - 1)
            {
                printf("%d\n", maze[row][col]);
            }
            else
            {
                printf("%d ", maze[row][col]);
            }
        }
    }

cleanup:
    // Free allocated memory
    if (maze != NULL)
    {
        for (int row = 0; row < totalRows + 2; row++)
        {
            free(maze[row]);
        }
        free(maze);
    }

    return exitCode;
}

I did not check the logic of your program - only added assertions and did general cleanup.

本文标签: cError in dynamically allocating memory for a 2D arrayStack Overflow