-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,294
  • 1
  • 15
  • 30
Harsh Savla
  • 47
  • 1
  • 6

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,710
  • 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,491
  • 6
  • 23
  • 32
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
  • 130,437
  • 16
  • 177
  • 247
0

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

strcpy(p[0], "hello");
chqrlie
  • 114,102
  • 10
  • 108
  • 170