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

Dani AI

Generated

Good catch by and . Two common ways this crashes: (1) no argument, so strlen(argv[1]) dereferences a null pointer; or (2) copying into a buffer that is one byte too small corrupts the heap, and the eventual fault shows up inside another libc call (often strlen or printf) because the heap metadata or terminator got smashed.

A couple of pragmatic improvements you can apply right away:

  • If you do not need your own copy, do not allocate at all. Once you have validated argc (as showed), just print the existing string.
puts(argv[1]);
  • If you really need an owned copy, consider strdup (POSIX) which allocates the right size and copies in one call. On MSVC use _strdup. Remember to free it when done.

  • If you want to stick with malloc/copy, avoid a double scan and the redundant assignment. strcpy returns dest, so there is no need to reassign name. Or copy exactly len+1 bytes:

size_t len = strlen(argv[1]);
char *name = malloc(len + 1);
if (!name) { perror("malloc"); return EXIT_FAILURE; }
memcpy(name, argv[1], len + 1);  /* includes the '\0' */

Debugging tip: turn memory bugs into immediate, precise errors. Compile and run with sanitizers or Valgrind:

gcc -g -O0 -fsanitize=address,undefined -fno-omit-frame-pointer main.c && ./a.out argument
valgrind --leak-check=full ./a.out argument

These tools will pinpoint the off-by-one write instead of reporting a later crash in strlen.

Recommended Answers

All 5 Replies

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.