Hello there, I am having a problem with small application. I have used gdb and following error appeared:

strlen() segmentation fault. Could anyone help me to find out solution?

int main(int argc, char* argv[]){

  char* name = malloc(strlen(argv[1]));

  name = strcpy(name, argv[1]);

  printf("%s \n", name);

  return EXIT_SUCCESS;
}

What input are you using? What is argv[1] in this case?

When running the program i am using ./name argument to pass argument to the program.

Argv1 should be argument passed to the program

First and foremost, the argv array always ends with a null pointer, so there's a possibility that either argv[1] won't exist, or it's NULL. You really need to check argc and act accordingly:

if (argc > 1)
{
    // argv[0] and argv[1] are safe to reference
}

Second, malloc(strlen(argv[1])) has an off by one error. strlen will return the number of characters up to but not including the null termination character, so you're not allocating enough memory to hold the complete contents of the string and its null character at the end. Add 1 to the result of strlen:

char* name = malloc(strlen(argv[1]) + 1);

Finally, malloc can fail and return a null pointer. You need to check this as well and act accordingly. General best practice is to free any memory you allocate as well. The full corrected code would be:

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

int main(int argc, char* argv[])
{
  if (argc > 1)
  {
    char* name = malloc(strlen(argv[1]) + 1);

    if (name != NULL)
    {
      name = strcpy(name, argv[1]);
      printf("%s\n", name);
      free(name);

      return EXIT_SUCCESS;
    }
    else
    {
      perror("Memory allocation failure");
      return EXIT_FAILURE;
    }
  }
  else
  {
    fputs("Insufficient arguments provided", stderr);
    return EXIT_FAILURE;
  }
}

Thank you very much for thorough explanation. I am new to programming and i struggle with argv. The code works perfectly now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.