2

This is my test code.

#include <stdio.h>

int main() {
    printf('c');
    return 0;
}

SO: ubuntu16.04

Compiler version: gcc5.3

Running the code above cause Segmentation fault error in "movdqu (%rdi),%xmm0 ".

I had google it, but I want to know why cause Segmentation fault

William Ardila
  • 1,049
  • 13
  • 22
kaiattrib
  • 101
  • 6

3 Answers3

0

Because you are trying to pring a char, not a string. First argument of printf() function is a format string. Strings are quoted in "", chars in ''.

Petr
  • 1,159
  • 10
  • 20
  • Thanks.I know print("c") is right. The detail in Segmentation fault is Illegal access to memory? I just want to know – kaiattrib Oct 31 '17 at 14:47
  • 1
    @kaiattrib The argument to printf is an address. printf is interpreting the character as an address outside of what the program is allowed to access. – BurnsBA Oct 31 '17 at 15:17
0

I fond the error when use GDB debug the program. image

Community
  • 1
  • 1
kaiattrib
  • 101
  • 6
  • I honestly don't understand at all this thing of posting links to pictures of text. Also: not an answer. – Useless Nov 01 '17 at 09:09
0

SHORT:

This is prototype of printf function in C:

int printf ( const char * format, ... );

You should pass c-string (like "this is my message") instead of char.

DETAILED:

This is prototype of printf function in C:

int printf ( const char * format, ... );

This means that the first argument should be a pointer to a null-terminated array of char. In fact, printf reads value of first argument which is address of an c-string in memory, then go to that address and reads bytes by bytes to reach null character. In two condition this code causes segmentation fault:

  1. The address is pointed by the first argument of printf is outbound of memory address of your program.
  2. printf can't find any null characters beginning from the specified address before reaching end of memory boundary of your program.

Please be careful about using non-pointer variables in place of pointers. This cause your program to crash without a argumentive reason.

SuB
  • 2,250
  • 3
  • 22
  • 37