Question

The program need to simply fill from keyboard a dynamically allocated matrix. I have to add that i included . I'm working on a C++ compiler thus i have to add the cast to malloc. It seems to have this error: "Unhandled exception at 0x0F92FB53 (msvcr120d.dll) in ConsoleApplication42.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD." while reaching at gets(a[i]) command. After debugging it seems to also have a very apropriate proble at free sequence.

int main()
{
    int n, i;
    char **a;
    printf("introduceti numarul de cuvinte:\n");
    scanf("%d", &n);
    a = (char**)malloc(n*sizeof(char*));
    if (!a)
        printf("alocare nereusita");

    for (i = 0; i < n; i++);
    {
        a[i] = (char*)malloc(56 * sizeof(char));
    }
    for (i = 0; i < n; i++)
    {
        printf("introduceti urmatorul cuvant:\n");
        gets(a[i]);
    }
    for (i = 0; i < n; i++)
        free(a[i]);
    free(a);
    return 0;

}
Was it helpful?

Solution

You have an extra semicolon after the first for-loop header!

OTHER TIPS

The answer above is correct.

Because of the extra ;, you are executing a[n] = ..., which is obviously a memory access violation.

In addition, if the user inputs more than 55 characters, your code will yet perform another memory access violation. Hence, recommending that you replacegets(a[i]) with the following piece of code:

#include <conio.h>

#define MAX_SIZE        (56-1)
#define ALLOWED_CHAR(c) (32 <= (c) && (c) <= 255)

int j = 0;

while (1)
{
    int c = _getch();
    if (j < MAX_SIZE && ALLOWED_CHAR(c))
    {
        a[i][j++] = (char)c;
        printf("%c",(char)c);
    }
    else if (j > 0 && c == '\b')
    {
        j--;
        printf("\b \b");
    }
    else if (j > 0 && (c == '\r' || c == '\n'))
    {
        a[i][j] = 0;
        break;
    }
}

You can redefine ALLOWED_CHAR if you want to limit the user-input, for example:

#define ALLOWED_CHAR(c)  ('0' <= (c) && (c) <= '9') // only digits
#define ALLOWED_CHAR(c)  ('A' <= (c) && (c) <= 'Z') // only capital letters
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top