-1

This is my code:

 #include<stdio.h>



    struct p{

           char* d;
           };

    typedef struct p* pt;

    int main(){
        pt opt;
        opt=(pt)malloc(sizeof(struct p));

        scanf("%s",(opt->d));


        printf("%s",opt->d);



        getch();

        return 0;

        }

Everytime I run it , it accepts and prints the string fine but an error occur. On debugging it tells that there is a segmentation fault but doesn't points to where it is? What is going wrong , It's seems to be fairly correct.

10111
  • 47
  • 10

5 Answers5

2

You used malloc to allocate space for your structure, but not for the string you want to read in. You need to do that too. Here's an example paraphrased from your question:

 pt opt = malloc(sizeof(struct p));
 opt->d = malloc(MAX_STRING_LENGTH);
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

Yupp, the problem is that you have to allocate memory for char * d;

1) Allocated the memory for char * d like (Mentioned in above reply)
opt->d = malloc(expected_max_len + 1);

2) Or you can declare buffer with maximum buffer length in structure:
char d[MAX_LENGTH];

GRAYgoose124
  • 621
  • 5
  • 24
unknown
  • 21
  • 2
1

the scanf put the scanned string to a char buffer. but in your code your char pointer is not pointing to any thing it should be pointed to a buffer

If your gcc> 2.7, you can use "%ms". this will allow to scanf to allocate memory for your pointer

scanf("%ms",(opt->d));
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

You have to allocate memory for char* d;

int main(){
    pt opt;
    opt=(pt)malloc(sizeof(struct p));
    opt->d = malloc( sizeof( char )* 80);
    scanf("%s",(opt->d));    //this might overflow
0

You need pass correct buffer to scanf not just point-to-somewhere pointer.

struct p{
   char* d;
};

typedef struct p* pt;

int main(){
    pt opt;
    opt=(pt)malloc(sizeof(struct p));

    opt->d = malloc(expected_max_len + 1);

    scanf("%s",(opt->d));


    printf("%s",opt->d);

    free(opt->d);


    getch();

    return 0;

}
RiaD
  • 46,822
  • 11
  • 79
  • 123