Consider the following C code snippet:
char *sentence = NULL;
strcpy(sentence, "Helloworld");
printf("%s", sentence); is the code segment correct or error.
If correct what is the output?
- Error
- Helloworld
- NuII,Helloworld
- None of the above
Consider the following C code snippet:
char *sentence = NULL;
strcpy(sentence, "Helloworld");
printf("%s", sentence); is the code segment correct or error.
If correct what is the output?
Answer: Error — the code invokes undefined behavior because sentence does not point to valid writable storage. That explains the runtime error reported by and matches ’s suggestion to try it. ’s direction (allocate or use storage) is correct; below are safe alternatives and brief troubleshooting tips.
#include <stdio.h>
int main(void) {
char sentence[] = "Helloworld"; /* storage is allocated on the stack */
puts(sentence);
return 0;
} #include <stdio.h>
int main(void) {
const char *sentence = "Helloworld"; /* point to a literal (read-only) — do not write to it */
printf("%s\n", sentence);
return 0;
} #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char *lit = "Helloworld";
size_t n = strlen(lit) + 1;
char *sentence = malloc(n); /* allocate, check result, then copy */
if (!sentence) return 1;
memcpy(sentence, lit, n);
puts(sentence);
free(sentence);
return 0;
} Notes and tips: always check allocation results and free dynamic memory. Avoid writing into string literals (use const char * when pointing at them). For debugging, compile with warnings and sanitizers (for example: -Wall -Wextra -g -fsanitize=address,undefined) or run under Valgrind to catch invalid writes.
Jump to Post— deceptikon 1,790This is clearly a homework or interview question, so please let us know what your thoughts are first.
Jump to Post— rubberman 1,355The pointer just points to NULL. It has no storage space. you need to allocate space. You could use strdup to do that. IE,
sentence = strdup("helloworld");strdup will allocate space for the string (including terminating NUL character) and copy the string to the newly allocated space that "sentence" now …
This is clearly a homework or interview question, so please let us know what your thoughts are first.
Why don't you just try it and see for yourself?
i tried. it says runtime error
The pointer just points to NULL. It has no storage space. you need to allocate space. You could use strdup to do that. IE, sentence = strdup("helloworld"); strdup will allocate space for the string (including terminating NUL character) and copy the string to the newly allocated space that "sentence" now owns.
i tried. it says runtime error
Then you have your answer. Wouldn't that have been easier than asking us to do your work for you?
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.