3

In the below pusedo code, the function display has char* as input parameter and a string "apple" is passed. In the function the elements of the string are accessed by index. Here there is no memory for the string "apple" then how this is getting accessed in the display function

#include <stdio.h>
void display(char * str)
{
   int i = 0;

  while ('\0' != str[i])
  {
   printf("%c", str[i]);
   i++;
  }
}

int main()
{
   display("apple");
   return 0;
}

The function works correctly and gives output as apple. This approach is seen in many programs but I would like to know where the memory will be assigned to the string "apple". And also what are the potential problems in this usage.

Ginu Jacob
  • 1,588
  • 2
  • 19
  • 35
  • Do not change the content. – BLUEPIXY Jun 27 '14 at 17:29
  • First of all, it is better to check, that `str!=0` in the very beginning of your function. But even this check can't guarantee, that your function will not try to access to wrong memory (outside allowed memory). Theoretically user of this function can put any pointer as parameter of the function. – Ilya Jun 27 '14 at 17:31
  • Sorry for the question asking about the memory. Since its hard to explain that part on the header kept in the body... – Ginu Jacob Jun 27 '14 at 17:33
  • 2
    Since you are not changing the input, change the type of the argument to `display` to `char const*`. – R Sahu Jun 27 '14 at 17:35

2 Answers2

7

Here there is no memory for the string "apple" then how this is getting accessed in the display function

Of course there is memory for the string "apple": string literals are placed in memory, and the literal itself serves as a pointer to that memory. The exact location is implementation-defined, but it is very common to place string literals in the memory segment occupied by the executable code of your program.

What are the potential problems in this usage?

None. As long as you do not try assigning into the memory of the string literal, you are safe.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Here there is no memory for the string "apple" then how this is getting accessed in the display function

The claim above is incorrect. There is memory allocated for string literals, it is just normally in a read-only section of memory, so there is nothing wrong with indexing into it.

However, because it is read-only, it should not be assigned to. See this question and this question for further discussions of string literals and their location in memory.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329