#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 13
int main(void)
{
// The pointer *s allocated on the stack
// The dynamic memory is allocated on the heap
char *s = (char *)malloc(SIZE * sizeof(char));
if (s == NULL)
{
perror("realloc() error");
return -1;
}
printf("s = %s (after malloc)\n", s);
strcpy(s, "c c++");
printf("s = %s (after strcpy)\n", s);
printf("s address = %p\n", s);
{
char *tmp = realloc(s, SIZE + 10);
if (tmp == NULL)
{
perror("realloc() error");
free(s);
return -1;
}
s = tmp;
}
printf("s = %s (after realloc)\n", s);
strcat(s, " java");
printf("s = %s (after strcat)\n", s);
printf("s address = %p\n", s);
free(s);
return 0;
}
/*
run:
s = (after malloc)
s = c c++ (after strcpy)
s address = 0000000000755730
s = c c++ (after realloc)
s = c c++ java (after strcat)
s address = 0000000000755730
*/