Why does this code crash?
Submitted by: AdministratorWhy does this code:
char *p = "hello, world!";
p[0] = 'H';
crash?
String constants are in fact constant. The compiler may place them in nonwritable storage, and it is therefore not safe to modify them. When you need writable strings, you must allocate writable memory for them, either by declaring an array, or by calling malloc. Try
char a[] = "hello, world!";
By the same argument, a typical invocation of the old Unix mktemp routine
char *tmpfile = mktemp("/tmp/tmpXXXXXX");
is nonportable; the proper usage is
char tmpfile[] = "/tmp/tmpXXXXXX";
mktemp(tmpfile);
Submitted by: Administrator
char *p = "hello, world!";
p[0] = 'H';
crash?
String constants are in fact constant. The compiler may place them in nonwritable storage, and it is therefore not safe to modify them. When you need writable strings, you must allocate writable memory for them, either by declaring an array, or by calling malloc. Try
char a[] = "hello, world!";
By the same argument, a typical invocation of the old Unix mktemp routine
char *tmpfile = mktemp("/tmp/tmpXXXXXX");
is nonportable; the proper usage is
char tmpfile[] = "/tmp/tmpXXXXXX";
mktemp(tmpfile);
Submitted by: Administrator
Read Online C Programming Job Interview Questions And Answers
Top C Programming Questions
☺ | Why does this code crash? |
☺ | What is wrong with this declaration? |
☺ | How can I read/write structures from/to data files? |
☺ | What does static variable mean in c? |
☺ | How can I increase the allowable number of simultaneously open files? |
Top Coding/Programming Categories
☺ | Python Interview Questions. |
☺ | OOP Interview Questions. |
☺ | Software engineering Interview Questions. |
☺ | PHP Interview Questions. |
☺ | VBA (Visual Basic for Applications) Interview Questions. |