For below sample code;
char* g_commands[]={
"abcd",
NULL
};
int main()
{
g_commands[1] = "efg";
char ** tmp = &g_commands[0];
for(; *tmp != NULL; tmp++){
printf("%s", *tmp);
}
return 0;
}
since tmp is pointing to the pointers in g_commands array in a loop, after I assign "efg" to g_commands[1], I expect the loop create a segmentation fault since the last element of g_commands is not null anymore. But the program finishes without exception and prints abcdefg successfully.
Why is it so? Does the compiler add NULL to the end of char* array as well?
The program has undefined behavior. In particular it means that a program can produce as an expected or as unexpected result.
I expect the loop create a segmentation fault since the last element of g_commands is not null anymore
The program works without a segmentation fault because the array g_commands
char* g_commands[]={
"abcd",
NULL
};
is defined in the global namespace and there is no other definition of an object after the array. Such a declaration has static storage duration and compilers usually set this memory to zeroes.
If you will move the definition in main like
#include <stdio.h>
/*
char* g_commands[]={
"abcd",
NULL
};
*/
int main()
{
char* g_commands[]={
"abcd",
NULL
};
g_commands[1] = "efg";
char ** tmp = &g_commands[0];
for(; *tmp != NULL; tmp++){
printf("%s", *tmp);
}
return 0;
}
then the probability that a segmentation fault will occur is very high.