2

I have been experimenting on strings in c. Here in this piece of code.

#include<stdio.h>
int main()
{
    char *arr="output";
    *arr='s';
    printf("%s",arr);
return 0;
}

Where in memory does the string "output" get created and as we have pointer arr(which resides in stack) which is initially pointing to this string,why is it not possible to assign some other char to the pointer? When I tried to run this program,I have seen run time error with signal:11 which is segmentation fault.

I have learnt that in c++, string "output" gets created in read only memory which causes 'deprecated conversion from string constant to ‘char*’ during compilation itself.What is behaviour in c?

Can someone explain me why this causes segmentation fault? And where is this string "output" gets created at the first place.

Thanks.

starkk92
  • 5,754
  • 9
  • 43
  • 59

2 Answers2

7

Where in memory does the string "output" get created

The array itself is static. It's unspecified whether it's in the same place as other string literal arrays with the same contents.

why is it not possible to assign some other char to the pointer?

Doing so gives undefined behaviour.

Can someone explain me why this causes segmentation fault?

Many implementations store the strings in write-protected memory, so that you get a fault if you try to. Note that in modern C++, the conversion to char* (rather than const char*) is not just deprecated but forbidden.

What is behaviour in c?

As in C++, it's undefined behaviour to attempt to modify the literal, and the implementation details aren't specified in either language. I'm a bit out of date with C, so I'm not whether the dodgy conversion to char* is allowed, deprecated, or forbidden these days.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 1
    All constant literals (and string literals which are of type `char[]` in C for historial reasons) can be potentially merged, irrespective of type. – Deduplicator Apr 29 '14 at 15:33
1

Here's a good resource to check out: https://www.cs.bu.edu/teaching/cpp/string/array-vs-ptr/

The main reason as stated, is that it is undefined behavior. As you have already allocated space for the character array with the first call of setting the value to output. Then you are trying to update the same array with maybe a different memory space. It is best to release the memory for the variable arr and then malloc new memory. Memory should be readonly after you write it and should be released after you are done. If you need new information and want to re-use a variable, then malloc new memory for it.

pmac89
  • 418
  • 1
  • 6
  • 23