The man page of realloc
states that unless the first argument of realloc
is NULL
, it must have been returned by an earlier call to malloc
, calloc
, or realloc
.
t = realloc (p, 14);
The above statement passes p
to realloc
, which points to the string literal "this is"
, which has static storage duration and is read-only though not const
qualified. As such, your program invokes undefined behaviour. (It crashed on my machine due to segfault.)
Also, you lose handle on the dynamically allocated memory when you reassign p
the address of the first element of the string literal, causing memory leak.
char *p =(char *) malloc ( 10 ),*t;
p = "this is";
What you actually need to do is copy the contents of the string literal to dynamically allocated buffer using strcpy
.
// include the required headers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// explicitly state void in the parameter list of main
int main(void) {
// do not cast the result of malloc
char *p = malloc(10 * sizeof *p);
char *t;
if(p == NULL) {
printf("malloc failed\n");
return 1;
}
// beware of buffer overrun by strcpy
// consider using the safer strncpy if it suits
p = strcpy(p, "this is");
if(strlen(p) == 7) {
// save the result of realloc in t
// in case, realloc fails to allocate
t = realloc(p, 14);
if(t == NULL) {
printf("realloc failed\n");
// handle it
// p points to old buffer
}
else {
t = NULL;
// p points to new buffer
}
}
// after your done with p, free it
free(p);
return 0;
}