ProgrammingHardIBM · Deloitte pattern
Assume a 64-bit LP64 ABI. What happens when this runs?
Assume a 64-bit LP64 ABI. What happens when this runs?
char *str = "hello";
str[0] = 'H';
printf("%s", str);- A. It prints Hello, with the first letter capitalised
- B. It prints hello, unchanged
- C. Undefined behaviour: str points at a read-only string literal, and modifying it is not allowed
- D. Compile-time error: string literals cannot be assigned to char*
Correct answer: C. Undefined behaviour: str points at a read-only string literal, and modifying it is not allowed
char *str = "hello"; makes str point at a string literal, which has static storage and is typically placed in read-only memory; attempting to modify it through str[0] = 'H' is undefined behaviour (often a segmentation fault on modern systems, but not guaranteed to crash everywhere). This is exactly why char str[] = "hello"; (a genuine, writable array copy) is used instead when modification is needed.
More C Programming questions
- Assume a 64-bit LP64 ABI. What is printed? c struct Flags { unsigned isActive : 1; unsigned isAdmin : 1; unsigned level : 6; }; struct…
- Assume a 64-bit LP64 ABI. What is printed? c union Data { int i; char c; }; union Data d; d.i = 0x12345678; printf("%x", (unsigned…
- Assume a 64-bit LP64 ABI. What is printed? c struct Point { int x, y; }; void tryModify(struct Point p) { p.x = 999; } int main(void) {…
- Assume a 64-bit LP64 ABI. What is printed? c struct Rect { struct { int x, y; } topLeft; struct { int x, y; } bottomRight; }; struct Rect…
- Assume a 64-bit LP64 ABI. What is printed? c typedef struct { int code; char message[20]; } Error; Error makeError(int c, const char msg)…
- Assume a 64-bit LP64 ABI. What is printed? c struct Counter { int value; }; void increment(struct Counter c) { c->value++; } int…