Manish Kumar Sharma
Manish Kumar Sharma

Reputation: 13442

pointer misdirection in the program

I have got this code in C. I am getting a strange behavior when running it on GCC-4.8.1(It compiles with no warnings and errors).
When I input r and c as any integer(r=c), I get to input the dynamically allocated 2D array but, when I input r and c say, 5 & 4 respectively(r>c), I get a don't send error in windows.I believe this maybe due to some illegal pointer indirection but I can't figure out what is it. Can you help me find it?
Here is the code:

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

int main()
{
    int no_of_test_cases;
    int r, c;
    int i,j;

    printf("Enter the no of test cases:\n");
    scanf("%d", &no_of_test_cases);
    printf("Enter the no of rows:\n");
    scanf("%d", &r);
    printf("Enter the no of columns:\n");
    scanf("%d", &c);

    r+=2;
    c+=2;
    //Dynamically allocate the 2D array
    char **string_pattern;
    string_pattern = (char**)malloc(r* sizeof(char*));
    if(string_pattern==NULL)
    {
        printf("Not enough memory");
        exit(0);
    }
    for(i=0; i<c; i++)
    {
        string_pattern[i] = (char*)malloc(c* sizeof(char));
        if(string_pattern[i]==NULL)
        {
            printf("Not enough memory");
            exit(0);
        }
    }
    //Now lets put a wall around with the character '#'
    j=0;
    for(i=0; i<r; i++)
    {
        string_pattern[i][j]='#';
    }
    j=0;
    for(i=0; i<c; i++)
    {
        string_pattern[j][i]='#';
    }
    j=c-1;
    for(i=0; i<r; i++)
    {
        string_pattern[i][j]='#';
    }
    j=r-1;
    for(i=0; i<c; i++)
    {
        string_pattern[j][i]='#';
    }
    printf("haha");
    //Now lets input the array
    for(i=1; i<r-1; i++)
    {
        for(j=1; j<c-1; j++)
        {
            scanf(" %c",&string_pattern[i][j]);   /*whitespace preceding the %c is to skip        
    a non whitespace character in the input buffer*/
        }
    }
    for(i=0; i<r; i++)
    {
        for(j=0; j<c; j++)
        {
            printf("%c",string_pattern[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Upvotes: 1

Views: 144

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36650

The immediate issue is that in your allocation loop, you are allocating memory for each row, but you are counting up to the number of columns (i < c):

for(i=0; i<c; i++) {
    string_pattern[i] = (char*)malloc(c* sizeof(char));
...

This needs to be

for(i=0; i < r; i++)
             ^^

Otherwise you are accessing an illegal index. **string_pattern allocates enough pointers for your given number of rows, but the for-loop which allocates memory for each row accesses invalid memory (e.g. r = 3, c = 4):

char **string_pattern = malloc(r* sizeof(char*));
+----+
| 0  |
+----+
| 1  |
+----+
| 2  |
+----+
. 3  .  <= Invalid index for c=3 in for-loop
......

Upvotes: 3

Related Questions