C Code Crashes from Memmove

My code does not crash when I write:

char s[44] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
memmove(s, "asdf", 5);

But it does when I write:

char* s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
memmove(s, "asdf", 5);

Does anyone know why?

3

3 Answers

first one allocates space and puts the a's in

second one is a pointer to constant memory, you aren't allowed to change it.

In the first case, 44 bytes are allocated on stack and the string "aa..a" is copied to this space. But in the second space, the string "aa..a" is a constant value and stored in the read only data segment. So a page fault will occur when you try to write a read only memory address.

1

char* s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

the string constant "aaaa" whatever is stored in a the memory which is readonly. For example in elf executables they will be stored in the .rodata section, which is nor writable. Therefore when you attempt to write at such a location it results in an errorhe

On the other hand char s[] will have the string stored in the local stack area, which you can modify.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest