I'm using Windows XP
I've been trying to expand the storage of a string
using the REALLOC() function and the program compiles
OK but when it's run it crashes. The same code is
compiled with Turbo C and it works OK.
sample code (copy from here and paste into your
editor of choice):
int main(void)
{
char s1;
char s2;
char *s3;
unsigned char i;
char c;
puts ("**** START
****");
s1 = "abcdef";
puts (s1);
s2 = "|ghijkl";
puts (s2);
system("PAUSE");
if ((s3 = (char *) realloc (s1, strlen(s1) + strlen
(s2) + 1)) == NULL) {
printf("Error with realloc #1\n");
exit (1);
} else {
printf ("adress of s1 = %ld\n", s1);
printf ("adress of s2 = %ld\n", s2);
printf ("adress of s3 = %ld\n", s3);
puts ("success allocating memory\n");
}
system("PAUSE");
strcat (s3, s2);
for (i = 0; i < strlen (s3) + 1; i++) {
c = (s3 + i);
if (c == '\0') {
putchar ('');
} else {
putchar (c);
}
putchar ('_');
}
putchar ('\n');
free (s1);
free (s2);
free (s3);
puts ("**** END
****");
system("PAUSE");
return 0;
}
sample C usage of realloc and strcat
Logged In: NO
This is not an error. From section 7.10.3.4 of the C spec,
void realloc(void ptr, size_t size);
"If ptr does not match a pointer earlier returned by the
calloc, malloc or realloc function ... the behavior is
undefined."
In the code sample posted, the first argument is static, not
allocated.
Logged In: NO
You are absolutely right. I've referred to section
7.20.3.4 (there was a typo in your reply "7.10.3.4") and
corrected my code - it works without a crash.
Thanks a million
regards
hf..