Mail Archives: djgpp/1996/07/08/14:07:52
Errors-To: postmaster AT ns1
From: "Michael Schuster" <Schuster AT eev DOT e-technik DOT uni-erlangen DOT de>
Organization: LS f. Elektr. Energieversorgung
Date: Mon, 8 Jul 1996 16:58:42 MEZ
Priority: normal
X-Mailer: Pegasus Mail for Windows (v2.23)
Content-Type: text
Content-Length: 1729
Gruess Euch!
I've written some programs with pointers and dynamic arrays, which
might not be very exiting, but I came to a very interesting point,
when using the realloc -function of libc.a.
I defined a pointer int* p, malloc'ed and then realloc'ed some more
space.(see source below)
When using p[a]= a for initialising the pointerposition a , everything worked fine.
I've never had an error. But when using *p=a; p=p+1;
there was an error. (I did realloc the pointer before p+1 of course)-
My super C- book (C-Grundlagen, Data Becker) told that this should
cause no error.
Somehow I had the idea to run it in a DOS Box (Win3.11) and there it
works now (see source-code). My conclusion is, that this must be the
DPMI server.
My question:
Which one behaves correctely? Or is a known thing which I' ve nerver
heard of?
Michi
--------------------------------------------
/* Dyn.c
Works fine in a DOS Box (Win 3.11) but doesnot work with native DOS
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p;
int a;
p=(int*) malloc(sizeof(int));
for (a=0;a<20;a++) {
p=(int*) realloc(p,sizeof(int)*(a+1)); /* resizing p*/
*p=a; /* init the pointer */
printf(" Nummer: %d \t %d \n", a,*p); /* debug info */
/* The crucial statement */
if (!(p==NULL)) p=p+1;
};
}
Your problem is that on the first iteration a==0 and
sizeof(int)*(a+1) = sizeof(int)
so p=p+1 results in p[1] while only p[0] is allocated. Also the next realloc
will not free the original memory. Try:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p, *q;
int a;
q = p=(int*) malloc(sizeof(int));
for (a=0;a<20;a++) {
*p=a; /* init the pointer */
printf(" Nummer: %d \t %d \n", a,*p); /* debug info */
/* The crucial statement */
q=(int*) realloc( q, sizeof(int)*(a+2) ); /* resizing p*/
if (!(q==NULL)) p=q+a+1;
};
}
--
Art S. Kagel, kagel AT quasar DOT bloomberg DOT com
A proverb is no proverb to you 'till life has illustrated it. -- John Keats
- Raw text -