Menu

#619 realloc/strcat/strcpy fail here but with Turbo C it works OK

open
nobody
None
5
2012-09-26
2006-01-09
Anonymous
No

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):

include <stdio.h>

include <stdlib.h>

include <string.h>

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;

}

Discussion

  • Nobody/Anonymous

    sample C usage of realloc and strcat

     
  • Nobody/Anonymous

    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.

     
  • Nobody/Anonymous

    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..

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.