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.

8 comments:

Anonymous 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.

rui 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.

Unknown said...

It is very useful to read about the computers, programming and operating system. thank you for sharing the blog with us

cdcdcdcd said...


Thanks for sharing this Post, Keep Updating such topics.

Deer Hunting Tips Camping Trips Guide DEER HUNTING TIPS travel touring tips

cdcdcdcd said...



I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.
Still Hunting Method
Hunting psych tips Survival Tips Travel Touring Tips

cdcdcdcd said...



I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.
travel trekking tips
see the link Tent Camping 101 Exploring Smithriver

Mrbk30 said...

Very Informative blog thank you for sharing. Keep sharing.

Best software training institute in Chennai. Make your career development the best by learning software courses.

android training in chennai
devops training in chennai
best devops training in chennai

Steps to install PyTorch on VMware workstation (Ubuntu guest)

  The following is the list of steps to install pytorch 2.0 in VMware workstation (Ubuntu guest): $ mkdir ~/pytorch $ mkdir ~/pytorch/as...