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

int main() {
    int size_to_alloc = sizeof(char*) * 1;
    char** p = (char**) malloc(size_to_alloc);
    p[0] = (char*) malloc (sizeof(char) * 10);
    strcpy("hello", p[0]);
    printf("%s\n", p[0]);
}

I am obviously missing something very basic but can't figure out what.

Punit Vara
  • 3,744
  • 1
  • 16
  • 30
amrka
  • 49
  • 1
  • 6
  • 8
    strcpy has the arguments in the wrong order. – keithmo Nov 30 '15 at 07:16
  • 1
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Nov 30 '15 at 07:17
  • Thanks for the answers. Marking the first answer by Dilip as accepted. – amrka Nov 30 '15 at 07:42
  • 1
    Dilip's answer is actually the last one ;-). All other answers were posted 15 minutes before, in the space of 1 minute. keithmo's comment was even faster, providing the correct answer in less than 2 minutes. – chqrlie Nov 30 '15 at 07:52
  • oh is it! changing accepted to yours. – amrka Nov 30 '15 at 09:16

4 Answers4

1

strcpy() function has argument mismatch.

usage of string copy as per the man page char *strcpy(char *dest, const char *src);

So your strcpy() call has to be strcpy(p[0], "hello");

Dilip Kumar
  • 1,736
  • 11
  • 22
0

Just make small change in strcpy function : char *strcpy(char *dest, const char *src).

dest : the destination array
src : string to be copied.

Like:

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

int main() {
    int size_to_alloc = sizeof(char*) * 1;
    char** p = (char**) malloc(size_to_alloc);
    p[0] = (char*) malloc (sizeof(char) * 10);
    strcpy(p[0],"Hello");      /* change */
    printf("%s\n", p[0]);
}

Output: Hello

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
0

Please read the man page of strcpy(). It says

char *strcpy(char *dest, const char *src);

So, you need to have the first argument as the destination (aka, copy to), second one as source (aka copy from).

In your case, "hello" has been supplied as the copy to address and "hello" being a string literal, attempt to copy anything into it (i.e.,modification of a string literal) will result in undefined behavior, which leads to the segmentation fault.

Solution: swap the arguments of the function call.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

strcpy takes its arguments in the opposite order: destination first, source second. Try:

strcpy(p[0], "hello");
chqrlie
  • 131,814
  • 10
  • 121
  • 189