0

I am just practicing to understand dynamic allocation in C. I am getting a segmentation fault error. I am not sure where I made mistake.

int wordcount = 5;
char **args = (char**)malloc(wordcount * sizeof(char*));

for ( int i = 0; i < wordcount; i++) {
    args[i] = (char*)malloc(167 * sizeof(char));
}

int c=0;
while(c < wordcount){
    strcpy("hello\n",  args[c]);
    c++;
}
9
  • 2
    Which documentation to strcpy() did you read? Commented May 19, 2018 at 16:54
  • "not sure where I made mistake" a debugger would point you to the line crashing the program. Commented May 19, 2018 at 16:56
  • 1
    It seems all you need is a good strcpy reference. By the way, just about any tutorial or book would have told you how to use strcpy already. Commented May 19, 2018 at 16:56
  • 1
    strcpy("hello\n", args[c]); ==> strcpy(args[c], "hello\n"); Commented May 19, 2018 at 16:59
  • 1
    Well no, char ** args; defines args to be a pointer to pointer to char. Also there is no data type "string" in C. Commented May 19, 2018 at 17:09

1 Answer 1

1

You are trying to copy args[c] to the location of the "hello\n" string, which is in read only memory, you should change the order of the parameters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.