-1

I'm terrible with C, and am having trouble with strcpy. I'm trying to grab one of the function arguments and store it in a char array. When I run this, I get a segmentation fault, but I don't see why. What am I doing wrong? Thanks!

struct bb_state {
    FILE *logfile;
    char *rootdir;
};

struct bb_state *bb_data;
bb_data = malloc(sizeof(struct bb_state));
strcpy(bb_data->rootdir, argv[argc-2]);
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • 1
    There is a need to ensure the area the pointer(`bb_data->rootdir`) is pointing. – BLUEPIXY Apr 12 '13 at 17:04
  • Did you check size of the `bb_data->rootdir` . In `char * strcpy ( char * destination, const char * source )` :To avoid **overflows**, the size of the array pointed by **destination** shall be long enough to contain the same C string as **source** (including the terminating null character), and should not overlap in memory with source. – Ritesh Kumar Gupta Apr 12 '13 at 17:07

3 Answers3

2

You must allocate memory for char* rootdir.

Example:

int len=strlen(argv[argc-2])+1;
bb_data->rootdir=malloc(len);

and after that you can do:

strcpy(bb_data->rootdir, argv[argc-2]);
Johnny Mnemonic
  • 3,822
  • 5
  • 21
  • 33
1

You need to allocate space for rootdir. Estimate how many characters you are trying to copy and you can do another malloc for rootdir:

Make sure argv is big enough to be indexed using argc-2. This could also cause crash.

bb_data->rootdir = malloc(strlen(argv[argc-2]+1)); 
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
cppcoder
  • 1,194
  • 4
  • 16
  • 30
1

I'm trying to grab one of the function arguments and store it in a char array.

The problem with your code is that you don't have a character array in which to store the copied argument. What you have is a pointer. You must allocate storage in which to copy the argument. Or, you can make rootdir be an array instead of a pointer, but you must be careful to prevent the copy from overflowing the fixed-size array.

Allocate storage

bb_data->rootdir = malloc(strlen(argv[argc - 2]) + 1); // +1 is for the NULL

Make rootdir an array

#include <limits.h>
#include <stddef.h>
#include <stdlib.h>

...

    struct bb_state {
        FILE *logfile;
        char  rootdir [PATH_MAX];
    };

    struct bb_state *bb_data;
    size_t           len;
    len = strlen(argv[argc - 2]);
    if (len >= PATH_MAX) {
        // Argument is too long.
        fprintf(stderr, "Argument is too long: %s\n", argv[argc - 2]);
        return EXIT_FAILURE;
    }
    bb_data = malloc(sizeof(struct bb_state));
    strcpy(bb_data->rootdir, argv[argc - 2]);
Dan Moulding
  • 211,373
  • 23
  • 97
  • 98