Ugh, segmentation fault.

I'm trying to get rid of this segmentation fault:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <string.h>
#include <time.h>

int main() {
    char* str = "Memmove is cool";

    printf("%s\n", str);

    memmove(str, str + 10, 1);

    printf("%s\n", str);

    return 0;
}


This produces a segmentation fault unless the third argument to memmove is 0.
Why? I tried figuring this out myself but it doesn't make sense. I've tried it on Linux and on windows and it didn't work on either :l

Never mind, it was the way I was using char* instead of "char myChar[]".
Last edited on
str is pointing to a location of memory which you cannot modify.
Change line 6 to char str[] = "Memmove is cool"; so you'll have an array which you can modify
I did :l

Never mind, it was the way I was using char* instead of "char myChar[]".
.

But thanks anyway. Now I know why, and that I can't modify C strings like that.

Now I have to try and do it in asm =[ I'm going to have nightmares tonight...
Last edited on
Bazzy is right.
Always remember diff betn array [] and pointer *
Array: you can modify any single memory location within array.
Pointer: You can change the memory location to which the pointer is pointing to.
Reverse is not true.
It's not as simple as that.
No, it never is...
char* str = "Memmove is cool" creates a pointer to a constant character string
char str[] = "Memmove is cool" creates a pointer to a mutable character string

I think...
Makes sense because arrays are pointers.

Thanks :)
To prevent these mistakes in the future, always assign string literals to const char *. The compiler will be able to catch the error because memmove() and other C functions from cstring take a 'char *'. 'const char *' cannot be implicitly converted to 'char *', but 'char *' can be implicitly converted to 'const char *'.

EDIT: Oh, and the reason char str[] is modifiable and const char *str isn't is because the former is syntactic sugar for
char str[] = {'M','e','m','m', /*(...)*/,0};
which implies copying an array to the stack at run time, while the latter makes a direct pointer to the string literal, and string literals are loaded to read-only memory.
Last edited on
SIGSEGV.

Sorry, helios, you've been terminated. You need ring 0 access for that.

But anyway, thanks.

"Syntactic sugar leads to cancer of the semi-colons"
I wonder what he was talking about?
Last edited on
Topic archived. No new replies allowed.