I am puzzled by this response.Can anyone help me on this and point out where I am making a mistake? The output at codepad is “memory clobbered before allocated block“
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s = (char *)malloc(10 * sizeof(char));
s = "heel";
printf("%s\n",s);
printf("%c\n",s[2]);
printf("%p\n",s);
printf("%d\n",s);
free(s);
return 0;
}
You’re trying to free constant memory with:
What you’re doing is allocating a piece of memory and storing its location (
char *s). You are then overwriting that reference with one to a string constant “heel” (memory leak), which cannot befreed. To make this behave as desired, you should be copying the constant string to the memory you allocated:Here is an example for getting user input: