-2

I'm trying to modify an array of char declared in main (tab). So i send it to modify_tab and i modify it. But it doesn't work and send me a Segmentation Fault. Here's my code :

  1│void    my_putstr(char *str)
  2│{
  3│  int   i;
  4│
  5│  i = 0;
  6│  while (str[i] != '\0')
  7│    {
  8│      write(1, &str[i], 1);
  9│      i++;
 10│    }
 11│}
 12│
 13│void    modify_tab(char *tab)
 14│{
 15│  char  *map;
 16│
 17│  map = tab;
 18│  map[3] = 'a';
 19│  my_putstr(map);
 20│}
 21│
 22│void    main()
 23│{
 24│  char  *tab;
 25│
 26│  tab = "0123456789\n\0";
 27│  my_putstr(tab);
 28│  modify_tab(tab);
 29│}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Difender
  • 495
  • 2
  • 5
  • 18
  • 2
    You can't modify a literal string (you have to malloc and initialize tab first). – Elliott Frisch Feb 15 '14 at 18:11
  • It would be helpful now for future visitors to the question and in the future to not include line numbers in the code you post since people may wish to paste the code and test it usually using an [online compiler](http://stackoverflow.com/questions/3916000/online-c-compiler-and-evaluator) which would be impossible as is. You want to make it as easy as possible for people to help you. – Shafik Yaghmour Feb 15 '14 at 18:29

2 Answers2

6

tab is pointing to a string literal and it is undefined behavior to modify a string literal. An alternative that would work would be a char array:

char  tab[] = "0123456789\n" ;

Note, you don't need to terminate a sting literal with a null, it will be terminated for you in this case and also in your original code.

The relevant quote from the draft C99 standard on modifying a string literal would be from 6.4.5 String literals paragraph 6 which says (emphasis mine going forward):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

and for null terminating the string literal would be back in paragraph 5

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.66) [...]

and in the case of initializing the array the section is 6.7.8 Initialization:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

As you have defined it, tab is not an array of characters, it is a pointer. To make tab be an array of characters, do this instead:

 char tab[] = "0123456789\n\0";
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132