0

In my book there is an example how to copy a character string (2 pointers). I copied the whole code but when I start the program in terminal it says "Segmentation fault (core dumped)" >.<

What is wrong with this code? :

#include <iostream>
#include <string>

using namespace std;


void cpy(char* p,const char* q){

    while(*p++ = *q++) ;
}

int main(){

    char* hello;

    cpy(hello, "Whazzap");

    return 0;
}

2 Answers2

4

Your program has Undefined Behavior, because you are using the value of an uninitialized variable (the hello pointer in this case).

You probably meant hello to be an array of characters. If so, declare it this way:

char hello[SIZE];

Where SIZE is a compile-time constant large enough to make sure the array will be able to hold all the characters you want to copy into it. If your goal is just to initialize the array with the string literal, you could simply do this:

char hello[] = "Whazzap";
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • 2
    In all respect, do you really think this answer will help the OP? – Stephan Dollberg Mar 15 '13 at 18:15
  • 1
    @bamboon: Yes. It tells him what is the source of his troubles, and also in a generalized way, which will hopefully save him from similar problems in future. – Andy Prowl Mar 15 '13 at 18:16
  • @bamboon What's wrong with Andy's answer? – Nik Bougalis Mar 15 '13 at 18:47
  • 1
    @NikBougalis There is nothing wrong with his answer, it's just that a term like "UB" without explanation is of no help to a beginner and the question indicates that there are some real basics missing and this band-aid solution will only fix this one problem but not the next ones which arise from this question. Also note that Andy has since improved his answer. – Stephan Dollberg Mar 15 '13 at 19:01
4

Your pointer hello is uninitialized. That means it points to some random memory location, to which you try to write in the cpy function. You are basically writing to locations you are not allowed to.

You need to allocate space for the copy by creating a char array, but you must make sure that there is enough space to copy the whole string.

Since it seems you are learning, I will point out that this approach is fraught with danger: whatever you do, you must ensure that you will not write beyond the bounds of the storage you created. Rest assured that the C++ standard library provides useful classes to deal safely with this kind of problem, so this should only be part of a learning process, and not something you do in real life programming.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480