在编写一个程序来反转一个字符串后,我无法理解为什么在尝试反转字符串时出现了seg故障.我在下面列出了我的程序.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse(char *);
int main() {
char *str = calloc(1,'\0');
strcpy(str,"mystring0123456789");
reverse(str);
printf("Reverse String is: %s\n",str);
return 0;
}
void reverse(char *string) {
char ch, *start, *end;
int c=0;
int length = strlen(string);
start = string;
end = string;
while (c < length-1){
end++;
c++;
}
c=0;
while(c < length/2){
ch = *end;
*end = *start;
*start = ch;
start++;
end--;
c++;
}
}
Run Code Online (Sandbox Code Playgroud)
第一个问题:
即使我只将1个字节的内存分配给char指针str(calloc(1,'\0')
),并且我将18个字节的字符串复制mystring0123456789
到其中,并且它没有抛出任何错误,并且程序在没有任何SEGFAULT的情况下工作正常.
为什么我的程序没有抛出错误?理想情况下它应该抛出一些错误,因为它没有任何内存来存储那个大字符串.有人可以对此有所了解吗?
该程序运行完美,并给我输出Reverse …