【发布时间】:2013-03-09 03:30:45
【问题描述】:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define SUCCESS 0
#define FAILURE -1
int str_rev(char **s, char **d){
int count = 0;
if(s == NULL || d == NULL){
printf("\n Invalid address received! \n");
return FAILURE;
}
else{
while(**s != '\0'){
**s++;count++;
}
while(count > 0){
**d++ = **s--;count--;
}
**d = '\0';
return SUCCESS;
}
}
int main(){
int ret_val = SUCCESS;
char *a = "angus";
char *b;
b = malloc((strlen(a) * sizeof(*a)) + 1);
ret_val = str_rev(&a,&b);
if(ret_val == FAILURE){
printf("\n String is not reversed! going to quit! \n");
free(b);
return FAILURE;
}
printf("\n b:%s \n",b);
free(b);
return SUCCESS;
}
我正在编写一个简单的程序,不使用预定义的字符串反转函数。但这给我带来了分段错误。我相信我正在访问正确的内存地址。
已编辑:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define SUCCESS 0
#define FAILURE -1
int str_rev(char *s, char **d){
int count = 0;
if(s == NULL || d == NULL){
printf("\n Invalid address received! \n");
return FAILURE;
}
else{
while(*s != '\0'){
s++;count++;
}
s--;
while(count > 0){
printf("\n *s:%c \n",*s); // prints the values correctly in the reverse order
*(*d)++ = *s--;count--;
printf("\n **d:%c \n",*((*d)-1)); // doesnt print the values, after the assignement
}
**d = '\0';
printf("\n s:%s *d:%s \n",s,*d); // both s and d doesnt print the values copied
return SUCCESS;
}
}
int main(){
int ret_val = SUCCESS;
char *a = "angus";
char *b,*x;
b = malloc((strlen(a) * sizeof(*a)) + 1);
x = b;
if(b == NULL){
}
ret_val = str_rev(a,&b);
if(ret_val == FAILURE){
printf("\n String is not reversed! going to quit! \n");
free(b);
return FAILURE;
}
printf("\n b:%s \n",b);
free(b);
return SUCCESS;
}
我修改了上面的代码,因为 'a' 包含字符串。因此,一个指针就足以指向该位置,因为不需要进行任何更改。但即使在上述更改之后,“s”中的内容也不会被复制到“d”。在打印“printf("\n b:%s \n",b);" 后出现段错误.
【问题讨论】:
-
ret定义在哪里? -
哪里是 ;在
printf("\n b:%s \n",b)之后? -
b = malloc(sizeof(b))将为char *分配空间。我想你需要b = malloc(strlen(a)+1)。 -
@Angus 了解如何使用编译器显示的警告以及如何调试。所有这些问题都可以通过使用它们来解决。
-
为了详细说明@Ganesh 的评论,
malloc(sizeof(b))将分配sizeof(b)字节(可能是4 或8 字节,具体取决于系统),因为b是一个指针。显然,这不足以存储长于几个字符的字符串,因此malloc(strlen(a)+1)是正确的。
标签: c