以下代码会导致段错误,在 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/