Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Segmentation Fault while using printf

This one is probably very simple, but I can't seem to get it working.

I have this very simple snippet 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);

}

Which causes a segmentation fault when I run it. GDB outputs:

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

But I still don't get it.

Comments would be appreciated, thanks.

like image 820
Hamza Avatar asked Jun 04 '10 16:06

Hamza


4 Answers

When you write

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

the *p will be the value at p[0] which is a character. The printf however is looking for an array of chars, thus causing it to segfault. Remember that in C, strings are just arrays of characters, and arrays are effectively pointers to the first element, this is why you don't need to dereference.

To fix this remove the * to get:

printf("%s\n", p);
like image 72
Il-Bhima Avatar answered Oct 14 '22 07:10

Il-Bhima


You're passing a character to printf; you should be passing the pointer.

char buf[100];
char *p = buf;

strcpy(p, "Test string");

printf("%s\n", p);     // p, not *p
like image 41
zildjohn01 Avatar answered Oct 14 '22 09:10

zildjohn01


Use this:

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

use "p" instead of "*p"

like image 4
Ehsan Avatar answered Oct 14 '22 09:10

Ehsan


Replace

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

with

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

When you use %s, printf expects you to pass a char*. You are passing a char instead.

like image 3
Eric Petroelje Avatar answered Oct 14 '22 09:10

Eric Petroelje