UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » core dump in string

#1 2012-02-09 04:56 PM

useless79
Member
Registered: 2011-10-10
Posts: 30

core dump in string

Why following code is giving core dump.

#include<stdio.h>

main()
{
  char *p = "hello";
  *p = 'm';

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

As of I know  neither pointer p is constant nor string.

thanks

Offline

#2 2012-02-09 09:36 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,833
Website

Re: core dump in string

Well, yes it is constant; it's a literal string!  Your pointer to it is not constant, and you've defined it so that it looks as if it's not pointing to constant memory; but, your initializing it to a string literal does indeed point it at a constant value that can't be changed...  (On some compilers, anyway...  Some will let you actually modify string literals, which I think is a pretty broken behavior...  Yours obviously stores them in a memory region with no write permission, which causes the seg-fault...)

What you probably wanted instead was:

char p[] = "hello";

Instead of defining a simple pointer and setting it to point at the constant string literal, that defines a stack buffer and initializes its contents with "hello" followed by a '\0'...  Then, you'd be able to modify the buffer contents, because it's all on your stack...  The string literal here is only used to initialize the starting contents of the buffer...

Alternatively, if you really wanted the pointer version, you could do:

char *p = strdupa ("hello");

That would also give you a stack-based copy of the string literal...  Or, you could use regular strdup() to get a dynamic heap-based copy...

Offline

#3 2012-02-09 11:05 PM

useless79
Member
Registered: 2011-10-10
Posts: 30

Re: core dump in string

thanks Rob. I got it.

Offline

  • Index
  • » C
  • » core dump in string

Board footer

Powered by FluxBB