0

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;
}
3
Contributors
5
Replies
17
Views
2 Years
Discussion Span
Last Post by Bartosz
0

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

0

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;
  }
}

Edited by deceptikon

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.