0

I have to write a program that stores and prints out integers from memory. I have to use realloc. Basically, the program allocates size for 2 ints. When input is given 2 ints it should reallocate space for 1 more int and prints out double. Next, when input is given 3 ints, it should allocate 2 more spaces for int and prints out double.. and so on..

Test cases:

input file in.0:
------
4
------

expected output:
------
4
------

=================================================

input file in.1:
------
4 5
------

expected output:
------
4
5
double
------

==================================================

input file in.2:
------
4 5 3
------

expected output:
------
4
5
double
3
double
------

===================================================

input file in.3:
------
4 5 3 2 9
------

expected output:
------
4
5
double
3
double
2
9
double

I wrote this program but it does not allocate memory properly. Can someone guide me in the write direction please?

int main(void)
{
    int c;

    int digit;
    int count = 0;
    int d_size = 1;
    int init_size = 2;
    int *p = (int *) malloc(sizeof(int) * init_size);

    while((c = scanf("%i", &digit)) != EOF)
    {
        if (c == 1)
        {
            *(p+count) = digit;
            count++;
        }
        else
        {
            printf("not valid");
        }

        printf("%i\n", digit);

        if (count >= 2)
        {
            printf("double\n");
            p = (int *) realloc(p, sizeof(int) * d_size);
            d_size = d_size * 2;
        }

    }
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
SharkTiles
  • 585
  • 3
  • 9
  • 22
  • 5
    Don't damn cast the damn return value of the damn realloc! –  Jun 27 '12 at 18:53
  • 4
    "does not allocate memory properly" - please be more specific. In what way does it not work? – Oliver Charlesworth Jun 27 '12 at 18:53
  • 3
    @H2CO3: +1 I have a canned comment for this because I see it *soooooo* often around here. This is not C++, don't cast the return value of `malloc` (or `realloc` in this case)! – Ed S. Jun 27 '12 at 18:55
  • 2
    +1 from me for you too. That makes my eyes vomit. –  Jun 27 '12 at 18:55

1 Answers1

4

Your init_size is 2, but your d_size is 1. First of all, make d_size equal to init_size. Second, you need to do d_size = d_size * 2 before the realloc so you would actually increase the size.


Side note: realloc will fail if out of memory. If you write:

p = realloc(p, ...);

in case of failure, you will lose the memory previously allocated. You should always use realloc like this:

enlarged = realloc(p, ...);
if (enlarged == NULL)
    // handle error
else
    p = enlarged;

Side note 2: You may end up changing type of your pointer. Better not repeat it. Instead of

int *p;
p = (int *)malloc(sizeof(int) * count);

write:

int *p;
p = malloc(sizeof(*p) * count);
Shahbaz
  • 46,337
  • 19
  • 116
  • 182