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?

  1. Error
  2. Helloworld
  3. NuII,Helloworld
  4. None of the above

Dani AI

Generated

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.

Recommended Answers

All 5 Replies

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.