Friday, October 24, 2008

pointer pitfall

Some C pointer fundamentals manage to fox even seasoned programmers.
For example, what is wrong with the following piece of code:

func() {

char *c;
c = "this is a string.";
*c = 'T';
printf("%s", c);
}


The code tries to capitalize the first letter of the string. It looks correct at first glance, but is not. It might even compile without any error, but will throw out an error when run.

4 comments:

Rand said...

Of course it will generate an error. Variable "c" is a pointer to the string and that pointer gets assigned to the address of a string constant. String constants aren't writable so you'll get an error when you try to modify it.

rtra said...

Actually, modifying a string constant is undefined behavior. There's a lot of platforms where that code works as expected.

Anonymous said...

Also, note why the string is a constant in this case? the string doesn't just belong to the pointer, but it might as well have been in use by some other variable - eg some compiler optimization might have resulted in the same string getting used by more than one pointer. as a result it is made a string constant and modifying it is an undefined behavior and wrong programming.

Anonymous said...

酒店打工

酒店兼職

台北酒店

打工兼差

酒店工作

酒店經紀

禮服酒店

酒店兼差

酒店上班

酒店PT

酒店

酒店喝酒

酒店消費

喝花酒

粉味

喝酒