c++ - 将 char 写入 char * 地址时出现段错误

标签 c++ c pointers segmentation-fault

我的小 C 程序有问题。也许你可以帮助我。

char* shiftujVzorku(char* text, char* pattern, int offset){
    char* pom = text;
    int size = 0;
    int index = 0;
    while(*(text + size) != '\0'){
        size++;
    }
    while(*(pom + index) != '\0'){
        if(overVzorku(pom + index, pattern)){
            while(*pattern != '\0'){
                //vyment *pom s *pom + offset
                if(pom + index + offset < text + size){
                    char x = *(pom + index + offset);
                    char y = *(pom + index);
                    int adresa = *(pom + index + offset);
                    *(pom + index + offset) = y;   // SEGMENTATION FAULT
                    *(pom + index) = x;   
                    //*pom  = *pom - *(pom + offset);
                    //*(pom + offset) = *(pom + offset) + *pom;
                    //*pom = *(pom + offset) - *pom;
                }
                else{
                    *pom  = *pom - *(pom + offset - size);
                    *(pom + offset - size) = *(pom + offset - size) + *pom;
                    *pom = *(pom + offset - size) - *pom;
                }
                pattern++;
            }
            break;
        }
        index++;
    }
    return text;
}

程序在做什么并不重要。也许有很多错误。但是,为什么我会在这一行出现 SEGMENTATION FAULT(对于目标,请参见代码)?我正在尝试在地址“pom + offset + index”的帮助下将一些 char 值写入内存空间。感谢您提供的一切帮助。 :)

最佳答案

您是否有机会像这样调用代码:

shiftujVzorku( "foobar", "xx", 0 );

如果是这样,您的代码将尝试写入字 rune 字,这在 C 语言中是非法的。您应该这样做:

char buf[] = "foobar";
shiftujVzorku( buf, "xx", 0 );

关于c++ - 将 char 写入 char * 地址时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3044386/

相关文章:

c++ - 如何将成员函数指针传递给采用常规函数指针的函数?

c++ - 似乎至少有两种方法可以进行回溯,这种特定的回溯方法是如何工作的?

c++ - 模块不在节点内(节点必须由 ned 模块中的@node 属性标记)

c++ - 如何安全地结束一个线程

c++ - 当多个高优先级线程在多个内核上运行时,Linux 内核无响应

c-select() 识别第一个 fd 未阻塞的 select for read/recv operation

c - 数组和指针的区别

c - 带指针的递归 -C

c - 相同值的最长序列,C,数组

c++ - 如何使用 LLVM API 获取全局变量的初始化器