Realloc error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mahiapkum
    New Member
    • Mar 2007
    • 35

    Realloc error

    Hello,
    I have a code which does malloc and does realloc,but whenever i free i get the fllowing error:
    *** glibc detected *** free(): invalid next size (fast): 0x0804a008 ***

    the code is as below:

    short* p;
    short i;
    p = (short*)calloc( 10, 2);
    for(i = 0; i < 10; i++){
    p[i] = i;
    }
    p = (short*)realloc (p, 20);
    for(i = 10; i < 20; i++){
    p[i] = i;
    }
    for(i = 0; i < 20; i++){
    printf("%d\n", p[i]);
    }
    free(p);
    return 0;

    whats wrong in my code???
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    As a tip, use calloc(10,sizeo f(short) ) instead of calloc(10,2) because a short might not have the same size on every system, and it makes your code more readable.

    The problem is that your reallocated block of memory is too small, use realloc(p, 20*sizeof(short ) ); only then does it make sense to assign to p[10] and upwards.

    Please use [code]...[/code] tags around your code.

    Comment

    Working...