This question already has an answer here:
- Array index out of bound in C 9 answers
I use malloc to allocate n (string length of y) bytes for x. However after copying y to x , I added 3 more characters including '\0' in x and i got no error.
Shouldn't I get an error for trying to assign values to unallocated memory since I've allocated space enough for only 10 characters? Is this undefined behavior?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int *argc,char **argv)
{
char *x,*y="123465412";
int i,n;
n=strlen(y);
x=(char *)malloc(sizeof(char)*n);
for(i=0; i<n ; i++)
x[i]=y[i];
x[i]='5';
x[i+1]='5';
x[i+2]='\0';
puts(x);
}