Thread: Why does this cause a SEG FAULT

  1. #1
    Registered User
    Join Date
    Jun 2014
    Posts
    16

    Why does this cause a SEG FAULT

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main(){
        char *test = (char*)malloc(64 * sizeof(test));
        strcpy(test, "this is a test of the char pointer");
        printf("%s\n",*test);
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Turning up your warning levels and compiling leads to a clue:

    Code:
    seg.c:9:19: warning: format specifies type 'char *' but the argument has type
          'char' [-Wformat]
        printf("%s\n",*test);
                ~~    ^~~~~
                %c
    1 warning generated.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Apart from that, you have the idiom for using malloc() wrong.
    Code:
       whatever_type *test = malloc(number*sizeof(*test));
    1) No explicit type conversion (aka typecast).
    2) The argument of sizeof() needs to be related to what is pointed at, not the pointer.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Jun 2014
    Posts
    16
    Thank you guys very much. I really appreciate it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. New to C, seg fault
    By Manske in forum C Programming
    Replies: 7
    Last Post: 03-01-2011, 03:05 AM
  3. Can someone help with my seg fault?
    By John_L in forum C++ Programming
    Replies: 23
    Last Post: 03-01-2008, 04:04 PM
  4. seg fault?
    By bazzano in forum C Programming
    Replies: 7
    Last Post: 03-09-2006, 06:36 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM