0

Possible Duplicate:
Memory Allocation char* and char[]

Why does the following program give a Segmentation fault in run-time ?

#include <stdio.h>
#include <string.h>
#include <malloc.h>

main()
{
    char * str = "Have a. nice, day :)";
    char * ptr;

    ptr = strtok( str, " .,");

    printf("%s",ptr);
 }

But if I use char str[] = "Have a. nice, day :)"; it gives me the output. Why is that i get the error even though strtok definition is char* strcpy( char * , const char * ) ???~

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rabi
  • 19
  • 2

2 Answers2

5

strtok modifies the argument, str points to a string literal, modifying a string literal causes undefined behavior. Initializing a non-const char* with a string literal is in fact deprecated.

When you write str[], str becomes a mutable array initialized with the string.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
0

strtok modifies the string passed to it. I suspect it has something to do with char * = "literal string" giving you a pointer to the string in the .data section, while char[] = "literal string" allocates a buffer on the stack, and copies the initial contents from the .data section.

user47559
  • 1,201
  • 8
  • 9