C segmentation fault-char pointers

后端 未结 3 1981
孤城傲影
孤城傲影 2021-01-28 06:36

I need help figuring out why I am getting a segmentation fault here. I have gone over it and I think I am doing something wrong with the pointers, but I can figure out what.

3条回答
  •  一个人的身影
    2021-01-28 06:55

    char* a;
    *a = 'a';
    /*SEGMENTATION FAULT HERE!*/
    

    There isn't any "there" there. You've declared a and left it uninitialized. Then you tried to use it as an address. You need to make a point to something.

    One example:

    char buffer[512];
    char *a = buffer;
    

    (Note buffer has a maximum size and when it falls out of scope you cannot reference any pointers to it.)

    Or dynamic memory:

    char *a = malloc(/* Some size... */);
    
    if (!a) { /* TODO: handle memory allocation failure */ }
    
    // todo - do something with a.
    
    free(a);
    

提交回复
热议问题