0
\$\begingroup\$

I am running Embedded C on some ARM Cortex-M4 target which facilitates with both ROM and RAM support. I have a character pointer in my code:

char *temp = "";

Later in code I am modifying the variable as:

itoa(some_integer, temp, 10);

When I compile the code, compiler puts *temp in ROM section which cause exception to raise when trying to perform itoa(,,) operation as constant variable can not be modified. My question is that why compiler is putting char *temp into ROM section?

\$\endgroup\$
4
  • 5
    \$\begingroup\$ ... Because it's a string literal, and string literals should not be modified. \$\endgroup\$ Commented Aug 22, 2017 at 16:32
  • 4
    \$\begingroup\$ And this is a question for StackOverflow. Which will get closed as 1 zillions duplicate. \$\endgroup\$
    – Eugene Sh.
    Commented Aug 22, 2017 at 16:33
  • 6
    \$\begingroup\$ I'm voting to close this question as off-topic because the question is about C programming, with no specific application to electronics. \$\endgroup\$
    – The Photon
    Commented Aug 22, 2017 at 16:34
  • 3
    \$\begingroup\$ I don't think you really understand how strings work in C. Even if the compiler allowed you to do that, you'd probably be overwriting some other variable's memory. \$\endgroup\$
    – brhans
    Commented Aug 22, 2017 at 16:34

1 Answer 1

3
\$\begingroup\$

My question is that why compiler is putting char *temp into ROM section?

It's not. If you don't believe me, try this temp = NULL;. That will execute just fine, proving that temp was stored in RAM, not ROM. Because temp is a variable, you are free to change its value.

What was stored in ROM was "", an empty string. Since the value of "" can't change, just as the value of 3 can't change, it makes sense to store it in ROM.

So what's wrong with:

itoa(some_integer, temp, 10);

At this point, temp points to the string literal "". You are trying to change the thing temp points to. But literals are constants, and temp points to a constant. So you are trying to change a constant. But you can't change a constant -- that's what makes it constant.

So, temp is a variable, and you can change its value. But it points to a constant. So you can't change the value of the thing it points to.

\$\endgroup\$
2
  • \$\begingroup\$ Fine explanation, and because it relates to low-level C aspects I think it isn't out of place on EE SE. \$\endgroup\$ Commented Aug 22, 2017 at 17:13
  • 1
    \$\begingroup\$ With a toolchain targeted for embedded systems, it would not be unusual to actually define the section you want your variable to reside in by an attribute-directive and to use a custom linker script to define placement in ROM,DRAM,SRAM, ...whatever. So it's completely up to you where things end up. \$\endgroup\$
    – Andreas
    Commented Aug 22, 2017 at 20:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.