F
Francois Grieu
I guess this program has undefined behavior, as far as ISO C
is concerned.
Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *CopyStr(const char* s)
{
size_t n;
char *p;
n = strlen(s)+1;
if ((p = malloc(n))==NULL)
exit(EXIT_FAILURE);
memcpy(p,s,n);
return p;
}
void ShortenStr(char* p)
{
size_t n;
n = strlen(p);
p = realloc(p,n); /* could this move p ? */
p[n-1] = '\0';
}
int main(void)
{
char *p;
p = CopyStr("0123456789abcdef");
ShortenStr(p);
/* if realloc moved p, it is invalid */
puts(p);
return(EXIT_SUCCESS);
}
François Grieu
is concerned.
Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *CopyStr(const char* s)
{
size_t n;
char *p;
n = strlen(s)+1;
if ((p = malloc(n))==NULL)
exit(EXIT_FAILURE);
memcpy(p,s,n);
return p;
}
void ShortenStr(char* p)
{
size_t n;
n = strlen(p);
p = realloc(p,n); /* could this move p ? */
p[n-1] = '\0';
}
int main(void)
{
char *p;
p = CopyStr("0123456789abcdef");
ShortenStr(p);
/* if realloc moved p, it is invalid */
puts(p);
return(EXIT_SUCCESS);
}
François Grieu