D
diegotorquemada
Hello,
As far as I understand realloc() should not modify the old array, however this does not seem to happen:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p, i;
size_t size=0;
printf("Size of the vector: ");
scanf("%d", &size);
p = (int *)malloc(size*sizeof(int));
if (p==NULL)
{
perror("malloc() failed\n");
exit(EXIT_FAILURE);
}
printf("p = %p\n", p);
for(i=0; i<size; i++)
{
p = i;
printf("%d, ", p);
}
printf("\b\b.\n");
printf("Now we will duplicate the size of the list: %d\n", size);
size *= 2;
p = (int *)realloc(p, size);
if (p==NULL)
{
perror("realloc() failed\n");
exit(EXIT_FAILURE);
}
printf("p = %p\n", p);
for(i=0; i<size; i++)
printf("%d, ", p);
printf("\b\b.\n");
free(p);
return 0;
}
I compile with:
[daalvarez@earendil ~]$ gcc -Wall -o 08_realloc 08_realloc.c
And I get:
[daalvarez@earendil ~]$ ./08_realloc
Size of the vector: 10
p = 0x84e4008
0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Now we will duplicate the size of the list: 10
p = 0x84e4008
0, 1, 2, 3, 4, 25, 0, 7, 8, 9, 0, 135121, 0, 0, 0, 0, 0, 0, 0, 0.
**
||
LOOK for the 5... not it is 25
Using:
[daalvarez@earendil ~]$ gcc --version
gcc (GCC) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
What am I doing wrong?
Kind regards,
Diego Andrés
As far as I understand realloc() should not modify the old array, however this does not seem to happen:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p, i;
size_t size=0;
printf("Size of the vector: ");
scanf("%d", &size);
p = (int *)malloc(size*sizeof(int));
if (p==NULL)
{
perror("malloc() failed\n");
exit(EXIT_FAILURE);
}
printf("p = %p\n", p);
for(i=0; i<size; i++)
{
p = i;
printf("%d, ", p);
}
printf("\b\b.\n");
printf("Now we will duplicate the size of the list: %d\n", size);
size *= 2;
p = (int *)realloc(p, size);
if (p==NULL)
{
perror("realloc() failed\n");
exit(EXIT_FAILURE);
}
printf("p = %p\n", p);
for(i=0; i<size; i++)
printf("%d, ", p);
printf("\b\b.\n");
free(p);
return 0;
}
I compile with:
[daalvarez@earendil ~]$ gcc -Wall -o 08_realloc 08_realloc.c
And I get:
[daalvarez@earendil ~]$ ./08_realloc
Size of the vector: 10
p = 0x84e4008
0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Now we will duplicate the size of the list: 10
p = 0x84e4008
0, 1, 2, 3, 4, 25, 0, 7, 8, 9, 0, 135121, 0, 0, 0, 0, 0, 0, 0, 0.
**
||
LOOK for the 5... not it is 25
Using:
[daalvarez@earendil ~]$ gcc --version
gcc (GCC) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
What am I doing wrong?
Kind regards,
Diego Andrés