我被 GCC 中的这段代码困住了
我正在 Linux 中的 GCC 中测试代码。到目前为止一切顺利,这是我试图实现的简单 SLOC... 运行代码后输出是:
<1>
<>
<>
但更令人印象深刻的是,当我更改 printf 行的顺序时给出不同的结果...... 这段代码有什么问题,关于这种情况你能帮我吗...... 谢谢 问候。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *vbStrReverse(char *pBuffer);
int main(){
printf("<%s>",vbStrReverse("1"));
printf("<%s>",vbStrReverse("123456"));
printf("<%s>",vbStrReverse(""));
}
char *vbStrReverse(char *pBuffer){
int size=strlen(pBuffer);
char *ptr =(char*) malloc(sizeof(char)*size+1);
int i;
int ax;
do
{
ax=*(pBuffer+i);
if (ax=='\0'){
*(ptr+i+1)='\0';
break;
}
*(ptr+i)=*(pBuffer+size-i-1);
i++;
} while (1);
return(ptr);
}
I was testing the code in GCC in Linux. So far so good, Here is simple SLOC that i tried to achive...
After running the code output is:
<1>
<>
<>
But more impressively when i change order of printf lines giving different results...
What is wrong with this code and about this situation could you please assit me...
Thanks
Regards.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *vbStrReverse(char *pBuffer);
int main(){
printf("<%s>",vbStrReverse("1"));
printf("<%s>",vbStrReverse("123456"));
printf("<%s>",vbStrReverse(""));
}
char *vbStrReverse(char *pBuffer){
int size=strlen(pBuffer);
char *ptr =(char*) malloc(sizeof(char)*size+1);
int i;
int ax;
do
{
ax=*(pBuffer+i);
if (ax=='\0'){
*(ptr+i+1)='\0';
break;
}
*(ptr+i)=*(pBuffer+size-i-1);
i++;
} while (1);
return(ptr);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

该函数具有未定义的行为。
对于初学者来说,变量
i
未初始化您的意思似乎是
在这个语句中,
垃圾可以包含在指针
ptr
指向的数组中,例如当源字符串为为空,分配数组之外的内存将被覆盖该函数可以通过以下方式声明和定义
The function has undefined behavior.
For starters the variable
i
was not initializedIt seems you mean
In this statement
a garbage can be included in the array pointed to by the pointer
ptr
for example when the source string is empty and the memory beyond the allocated array will be overwrittenThe function can be declared and defined the following way