Here is my code.
int main()
{
char *s;
int i = 0;
printf(\"%lu \\n\", sizeof(s));
s = malloc(sizeof(char) * 2);
printf(\"%lu \\n\", sizeof(s
In illustration (and complete agreement with) @Ed S's answer, Try this example of your code with the small additions of an additional variable declared exactly the same way and malloc'ed right after the char *s
.
Although no guarantees that the variables are stored sequentially in memory, creating them this way makes it a high probability. If so, char *t
will now own the space that char *s
will encroach on, and you will get a seg fault:
int main()
{
char *s;
char *t;//addition
int i = 0;
printf("%lu \n", sizeof(s));
s = malloc(sizeof(char) * 2);
t = malloc(sizeof(char) * 2);//addition
printf("%lu \n", sizeof(s));
/*Why is this working?*/
while (i <= 5)
{
s[i] = 'l';
i++;
}
printf("%s \n", s);
printf("%lu \n", sizeof(char));
printf("%lu \n", sizeof(s[0]));
}
Note: In the environment I use, (Windows 7, NI Run-Time, debug, etc) I get a seg-fault either way, which somewhat supports the undefined behavior assertions in other answers.