c - 直接内存访问的段错误

标签 c string segmentation-fault

以下代码会导致段错误,在 GDB 中运行时,当更改内存以将字符减少 32 时,会出现该错误。

#include <stdio.h>

char *upper(char *);

int main(void) {

    char *my_word = "hello";

    printf("Upper: %s\n", upper(my_word));

    return 0;
}

char *upper(char *string) {
    while(*string != '\0') {
       *string -= 32;
        string++;
    }

    return string;
}

最佳答案

当您在末尾使用string++时,它将指向\0

char *upper(char *string) {
    while(*string != '\0') {
       *string -= 32;
        string++; // don't use this method here
    }
    return string; // it will return the address of \0
}

返回时会返回\0的地址。所以它不会打印任何东西。

尝试以下更改-

#include <stdio.h>
#include<string.h>
char *upper(char *);

int main(void) {

        char my_word[] = "hello";

        printf("Upper: %s\n", upper(my_word));

        return 0;
}

char *upper(char *string) {
        int i;
        for(i=0;string[i];i++)
                string[i] -=32;
        return string;
}

关于c - 直接内存访问的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25311777/

相关文章:

c++ - 在指针迭代中使用 for 循环时出现段错误

android - 蓝牙串口通讯,HC-06模块转安卓手机

c - 什么时候使用枚举?

c - 头文件中的数组声明

c - C中的二维字符数组操作

python - 在Python中检查字符串是否只包含一种类型的字母的更简单方法

java - 在java中将美国日期转换为欧盟日期

更改不相关的代码会导致段错误。它为什么要这样做?

c - 为结构指针执行 malloc 时出现段错误

c - C 中的堆栈输出