vam*_*olu 2 c string segmentation-fault
尝试运行以下函数时出错:
char* reverseInPlace(char* src)
{
//no need to alloc or free memory
int i=0;
int size=mystrlen(src);
for(i=0;i<size;i++)
{
int j=size-i-1;
if(i<j)
{
char temp;
printf("Interchange start %d:%c with %d:%c",i,src[i],j,src[j]);
temp=src[i];
src[i]=src[j];//error occurs here
src[j]=temp;
printf("Interchange complete %d:%c and %d:%c",i,src[i],j,src[j]);
}
}
return src;
}
Run Code Online (Sandbox Code Playgroud)
我把这个代码称为:
char* rev2=reverseInPlace("BeforeSunrise");
printf("The reversed string is %s\n",rev2);
Run Code Online (Sandbox Code Playgroud)
错误如下所示:
Interchange start 0:B with 12:e
Process terminating with default action of signal 11 (SIGSEGV)
Bad permissions for mapped region at address 0x401165
Run Code Online (Sandbox Code Playgroud)
为什么会出现此错误?
您将一个常量字符串传递给您的函数.
字符串文字在C char [N + 1]中N是类型(其中是数组的长度),但修改它们会导致未定义的行为.您的编译器应该已经在此时发出警告.
如果您想修改它,那么您必须创建一个副本:
char str[] = "BeforeSunrise";
char* rev2=reverseInPlace(str);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10780 次 |
| 最近记录: |