Search code examples
cpointersdynamic-arraysmemset

C language: How to use memset to reset dynamic 2d array?


everyone!

I know that calloc can allocate memory on heap for dynamic 2d array and initialize the memory to '\0'. However, after I have used the dynamic array, I want to reset it to zero again. The source code I wrote is below:

First of all, I defined macro as follow:

#define MAX_NR_VERTICES         5000
#define MAX_NR_VERTICESdiv8     625

#define REPORTERROR(file_name, line_num, message)   \
    printf("[%s--%d] %s\n", file_name, line_num, message)

#define CALLOC(arg, type, num, file_name, line_num, message)    \
if ((arg = (type *)calloc(num, sizeof(type))) == NULL) {    \
    REPORTERROR(file_name, line_num, message);  \
    exit(EXIT_FAILURE); \
}

#define FREE(arg)   \
    free(arg)

Then, I defined dynamic array and used it as follow:

...
char **graph = NULL;
    CALLOC(graph, char *, MAX_NR_VERTICES, __FILE__, __LINE__, "cannot allocate memory for char **graph in _tmain function.\n");
    for (int i = 0; i < MAX_NR_VERTICES; i++) {
        CALLOC(graph[i], char, MAX_NR_VERTICESdiv8, __FILE__, __LINE__, "cannot allocate memory for char (*g) [] in _tmain function.\n");
    }
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            graph[i][j] = 0x80;
            printf("%d ", graph[i][j]);
        }
        printf("\n");
    }
...

Everything was working well up to now. Then, I wanted to reset the dynamic 2d array to zero again:

memset(graph, 0, MAX_NR_VERTICES * MAX_NR_VERTICESdiv8 * sizeof(char));

The error occurred. The error information was:

Unhandled exception at 0x0FDA3FD4 (msvcr120d.dll) in 0xC0000005: Access violation writing location 0x0074F000.

What is the mistake in my program and how to use memset correctly here if I want to reset dynamic 2d array?

I use Visual Studio 2013 (C++) ultimate edition.

Thank you very much!


Solution

  • It appears that you've assumed that all the memory allocated for the elements of graph are contiguous. That's not a valid assumption. You'll need to reset the contents of each element of graph separately:

    for(i = 0 ; i < MAX_NR_VERTICES; i++)
      memset(graph[i], 0, sizeof(char) * MAX_NR_VERTICESdiv8);
    

    Best of luck.