-1
#include<stdio.h>
#include<stdlib.h>

int main() { 
    int *p;
    int m=40;
    p=(int *)malloc(sizeof(int)*10);
    while(realloc(p,10*sizeof(int))
        m=m+40;
    printf("Number of bytes allocated for heap",m);
}

what's wrong with this program

trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

2

realloc(p,10*sizeof(int) always allocates the same range of memory. Change it to p = realloc(p,m*sizeof(int). If realloc succeeds it returns the pointer to the new dynamic memory by its return value, and the memory pointer passed to it gets freed (the data behind the pointer is moved from old memory to new memory). If realloc fails to allocate memory it returns NULL, no memory is allocated and no memory is freed. Further you should always free the allocated memory. Adapt your code like this:

int main() { 
    int *p = NULL;
    int  m = 40;
    int *newP;
    do
    {
        newP = realloc( p, m*sizeof( int ) );
        if ( newP != NULL )
            p = newP;
        m = m+40;
    }
    while ( newP != NULL );
    free( p );
    printf("Number of bytes allocated for heap",m);
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • The OP's earlier question was so poorly asked it was deleted by moderators. Essentially, this is the same. Plus 1, but I question your effect of re-using `p`. Doesn't it cause UB on the first reuse, after OP ignored the return value from `realloc`? – Weather Vane Jan 20 '16 at 17:46
  • @WeatherVane I edited my code. (I think now it is obvious) – Rabbid76 Jan 20 '16 at 17:56
1

1) You have a mistake in your printf format string, you need to actually tell it to print the integer you're passing: %d or %i

2) You're reallocing the same number of bytes with every call, you need to increase it.

3) To be fully standards compliant, use int main(void).

4) See here to find out why not to cast the result of malloc in C.

5) realloc can accept a NULL pointer and the result is well-defined, so your initial malloc call is not needed anyway.

6) Use a named constant + sizeof(type/variable) to make your code more robust and maintainable (and correct, because sizeof(int) need not be 4).

All these things combined, here's how I'd rewrite your code:

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

#define REALLOC_NUM_ELEMENTS 10

int main(void) 
{
    int *p = NULL;
    int m = 0;

    while (p = realloc(p, (m + REALLOC_NUM_ELEMENTS * sizeof(int))))
        m += REALLOC_NUM_ELEMENTS * sizeof(int);

    printf("Number of bytes allocated for heap %d\n", m);
}
Community
  • 1
  • 1
user4520
  • 3,401
  • 1
  • 27
  • 50