So it is my understanding that a C string of, for instance “0123456789”, would actually occupy an array of 11 chars, 10 chars for the body and one for the terminating null. If that is true then why does the code below NOT cause some sort of error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv){
char * my_string = "0123456789";
/* my string should occupy 11 bytes */
int my_len = strlen(my_string);
/* however, strlen should only return 10,
because it does not count the null byte */
char * new_string = malloc(my_len);
/* allocate memory 10 bytes wide */
memcpy(new_string, my_string, my_len);
/* copy the first 10 bytes from my_string to new_string
new_string should NOT be null terminated if my understanding
is correct? */
printf("%s\n", new_string);
/* Since new_stirng is NOT null terminated it seems like this should
cause some sort of memory exception.
WHY DOES THIS NOT CAUSE AN ERROR?
*/
return 0;
}
Since new_string is not null terminated I would expect printf to just read forever until it reaches some other applications memory, or a randomly placed 0x00 somewhere and either crash or print something strange. What’s going on?
You have created undefined behavior. The behavior is compiler and platform dependent. It could crash. It could work. It could make you toast. It could collapse your computer into a singularity and absorb the solar system.
In your case, it’s likely that the memory at
new_string[11]was already0, which is'\0', or the terminating-null character.