1

I have a pointer to my struct gsa_sentence which has a struct member of type char* called untouched_sentence.

My goal is to copy a line from a file, into this struct variable using strcpy, but I am getting a segmentation fault on the strcpy function call.

structure:

typedef struct gsa_sentence{

    char *untouched_sentence;
    char *sentence_id;
    char mode;
    int fix;
    int sv_1;
    int sv_2;
    int sv_3;
    int sv_4;
    int sv_5;
    int sv_6;
    int sv_7;
    int sv_8;
    int sv_9;
    int sv_10;
    int sv_11;
    int sv_12;
    int pdop;
    int hdop;
    int vdop;

}gsa_sentence;

strcpy call:

   gsa_sentence* gsa;

   gsa = malloc(sizeof(gsa_sentence));
   printf("%s", line);
    if(gsa != NULL){
       strncpy(gsa->untouched_sentence, line, strlen(line));
       printf("%s", gsa->untouched_sentence);
        }

I have used strcpy elsewhere in my code and it works fine, I cannot figure out what is going on.

The gdb debugger says it's definately on the strcpy function call

chris edwards
  • 1,332
  • 4
  • 13
  • 31
  • hard to say when you've omitted your definition of `line`. That said, you should avoid using `strcpy`. Use the safer `strncpy`. – Red Alert Mar 11 '14 at 00:51

4 Answers4

4

Strcpy is attempting to copy characters into an uninitialized character buffer. You'll want to malloc space for untouched sentence," as well, or reassign untouched sentence to the memory address of line.

Alternatively, you could change the definition of the struct to include allocated memory by default:

typedef struct gsa_sentence{

    char untouched_sentence[50];
    char sentence_id[50];
...
Russell
  • 56
  • 1
  • 3
3

You need to allocate memory for gsa->untouched_sentence before copying data. You are only allocating memory for the structure itself.

trogdor
  • 1,626
  • 14
  • 17
2

You have to allocate memory to gsa->untouched_sentence

gsa->untouched_sentence = malloc ( strlen ( line ) + 1 );
KikoV
  • 899
  • 6
  • 13
-1

You must allocate space for your string: all characters, plus delimiter.

malloc (sizeof (gsa)) does NOT do this: "sizeof (gsa)" just returns enough for a pointer - not your entire string.

'malloc (sizeof (gsa_sentence))or 'malloc (sizeof (gsa_sentence)+1) would be better. But I'm not sure that's what you want, either.

FoggyDay
  • 11,962
  • 4
  • 34
  • 48