0
#include <stdio.h>
#include <string.h>

int main(void) {
    char *w;
    strcpy(w, "Hello Word");
    printf("%s\n", w);
    return 0;
}

What is wrong with the way the char pointer is used in the above code?

quantum
  • 1,400
  • 6
  • 21
  • 34
  • Not quite sure why you want to do that, but if a situation in which you need to do that comes up, you may find strdup() of use. – Corbin Mar 13 '12 at 02:39
  • 1
    http://stackoverflow.com/questions/3584926/char-pointers-segmentation-fault , http://stackoverflow.com/questions/2868884/whats-wrong-with-strcpy –  Mar 13 '12 at 02:58

4 Answers4

4

You allocate no space for the string. w is just a pointer to some memory (garbage value since it's not initialized).

char w[32];

or

char *w = malloc(32);

You need to allocated the space for the characters.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
3

No memory allocated.

Add

w = (char *)malloc(42);
Java42
  • 7,628
  • 1
  • 32
  • 50
3

It's an uninitialized pointer. The strcpy will write to some unknown location in memory.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

Ok, you did not ask to the system for memory, to use it with the string. This code will work

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
   char w[11];
   strcpy(w, "Hello Word");
   printf("%s\n", w);
   return 0;
}

That code declare w as an array of char, reserving the memory space for it. Other alternative is to use malloc or calloc for the char pointer. Read about that.

LuisEspinoza
  • 8,508
  • 6
  • 35
  • 57