C: Segmentation error when using printf

This is probably very simple, but I can't get it to work.

I have this very simple piece of code:

#include <stdio.h> #include <string.h> int main(void) { char buf[100]; char *p = buf; strcpy(p, "Test string"); printf("%s\n", *p); } 

This causes a segmentation error when it starts. GDB Outputs:

 Program received signal SIGSEGV, Segmentation fault. 0xb76af3b3 in strlen () from /lib/i686/cmov/libc.so.6 

But I still do not understand.

Comments will be appreciated, thanks.

+4
source share
6 answers

When you write

 printf("%s\n", *p); 

the *p will be the value in p[0] , which is a character. However, printf is looking for an array of characters, which causes it to segfault. Remember that in C, strings are just arrays of characters, and arrays effectively point to the first element, so you don't need to cast.

To fix this, delete * to get:

 printf("%s\n", p); 
+11
source

You pass the printf character; you should pass a pointer.

 char buf[100]; char *p = buf; strcpy(p, "Test string"); printf("%s\n", p); // p, not *p 
+10
source

Use this:

 printf("%s\n", p); 

use "p" instead of "* p"

+4
source

Replace

 printf("%s\n", *p); 

from

 printf("%s\n", p); 

When you use %s , printf expects you to pass char* . Instead, you pass a char .

+3
source

just pass the string (pointer):

 printf("%s\n", p); 

If you want to print the first char, then:

 printf("%c\n", *p); 
+2
source

% s calls printf () to dereference * p. Suppose the string was "Test string". Then on my Solaris box: (in the test program) p will "target" the address 0x54657374. The likelihood that this particular address is part of your process space is near zero.

This is what caused the SIGSEGV (segfault) signal.

0
source

Source: https://habr.com/ru/post/1311892/


All Articles