Is it possible to modify a string of char in C?

前端 未结 9 1359
小蘑菇
小蘑菇 2020-11-22 09:08

I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it\'s possible to change a char point

9条回答
  •  庸人自扰
    2020-11-22 09:41

    All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int take_me_back_to_DOS_times(const void *ptr, size_t len);
    
    int main()
    {
        const *data = "Bender is always sober.";
        printf("Before: %s\n", data);
        if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
            perror("Time machine appears to be broken!");
        memcpy((char *)data + 17, "drunk!", 6);
        printf("After: %s\n", data);
    
        return 0;
    }
    
    int take_me_back_to_DOS_times(const void *ptr, size_t len)
    {
        int pagesize;
        unsigned long long pg_off;
        void *page;
    
        pagesize = sysconf(_SC_PAGE_SIZE);
        if (pagesize < 0)
            return -1;
        pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
        page = ((char *)ptr - pg_off);
        if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
            return -1;
        return 0;
    }
    

    I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).

    Hope it helps. Good Luck!

提交回复
热议问题