-1

I have a problem with the c function 'strcpy' that I have not been able to figure out.

it involves copying to a char *[] like Argv (but not actually Argv). I can copy out of the structure but not in. But only if I initially declare the entire Argv Structure in a single go.

I assume that a char *[] is and array of char*.

Here is a simple demo program of the issue:

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

char FN[]="BBBB";   

char *TL[]={
 "a0                ",
 "a1                ",
 "a2                ",
 "a3                ",
 "a4                ",
 "a5                "};

 char BN[]="c1                    ";

 char N0[]="N0                    ";
 char N1[]="N1                    ";
 char N2[]="N2                    ";
 char N3[]="N3                    ";
 char N4[]="N4                    ";
 char N5[]="N5                    ";

 char* TD[6]; 


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

    // FN is a pointer to an array of chars
    // BN is the same

    //TL is an array of pointers (that each point to an array of chars)

    //TL[1] is thus a pointer to an array of chars

    //TL is the same structure as Argv

    //TD is the same structure as Argv  (but built up from parts)
    //  but is spread out across the globals and the main func.
    //  thus less easy to read and understand then TL.

    //TL[i], TD[i], and BN are initially allocated significantly larger than FN
    //  to remove the worry of overruns.

    //copy "a1                \0" into the space held by "c1   "
    strcpy(BN,TL[1]); //works

    //copy "BBBB\0" into the space held by "c1   "
    strcpy(BN,FN); //works

    TD[0]=N0;
    TD[1]=N1;
    TD[2]=N2;
    TD[3]=N3;
    TD[4]=N4;
    TD[5]=N5;

    //copy "BBBB\0" into the space held by "a1   "
    strcpy(TD[1],FN); //works

    //copy "BBBB\0" into the space held by "a1   "
    //strcpy(TL[1],FN); //dies



}

2 Answers2

4

Your char pointers point to string literals. Those are not writable. Even though their type is char* for historical reasons, you should always treat them as char const *.

Either malloc space for your char buffers, or use an array of arrays.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

As the link posted by dasblinkenlight in comments above,

char * p = "xyz"; is different from 

char p[] = "xyz"; 

The first is immutable, second is mutable.

Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?

Community
  • 1
  • 1
Mike Makuch
  • 1,788
  • 12
  • 15