我是 C 编程的初学者。在处理一个简单的任务时,我的代码因分段错误而崩溃。当我用 gdb 调试时,我发现从“manchester”方法返回的指针与 main 中分配的指针“encoded”不同。
我的代码如下
#include <stdio.h>
#include <stdlib.h>
char* manchester(char* bitstring);
char* differential_manchester(char* bitstring);
int main(){
int method;
scanf("%i\n", &method); //scan the method to encode
char* bitstring = (char *) malloc(100*sizeof(char)); // assumed max length = 100
scanf("%s", bitstring);
char* encoded;
if(method == 0){
char* encoded = manchester(bitstring); // where the confusion occur
}
else if (method == 1){
char* encoded = differential_manchester(bitstring);
}
printf("%s", encoded);
free(encoded);
free(bitstring);
return 0;
}
char* manchester(char* bitstring){
char* encoded_st = (char*) malloc(200*sizeof(char));
int i = 0, j = 0;
while (bitstring[i] != '\0' ){
if (bitstring[i++] == '0'){
encoded_st[j++] = '1';
encoded_st[j++] = '0';
}
else{
encoded_st[j++] = '0';
encoded_st[j++] = '1';
}
}
encoded_st[j++] = 0; //append null character at end
return encoded_st;
}
char* differential_manchester(char* bitstring){
//TODO: yet to implement
return NULL;
}
gdb调试
(gdb) b encode.c:14
Breakpoint 1 at 0x1222: file encode.c, line 14.
(gdb) run
Starting program: /home/ishad/Desktop/computer communication/a.out
0
1010
Breakpoint 1, main () at encode.c:14
14 if(method == 0){
(gdb) n
15 char* encoded = manchester(bitstring);
(gdb) s
manchester (bitstring=0x7ffff7e5a2d4 <__GI___libc_malloc+116> "I\211\300H\205\300\017\204\300") at encode.c:27
27 char* manchester(char* bitstring){
(gdb) n
28 char* encoded_st = (char*) malloc(200*sizeof(char));
(gdb) n
29 int i = 0, j = 0;
(gdb) n
30 while (bitstring[i] != '\0' ){
(gdb) n
31 if (bitstring[i++] == '0'){
(gdb) n
36 encoded_st[j++] = '0';
...
(gdb) n
30 while (bitstring[i] != '\0' ){
(gdb) n
40 encoded_st[j++] = 0; //append null character at end
(gdb) n
41 return encoded_st;
(gdb) p encoded_st
$1 = 0x555555559720 "01100110"
(gdb) n
42 }
(gdb) n
main () at encode.c:20
20 printf("%s", encoded);
(gdb) p encoded
$2 = 0x7fffffffdec0 "\001"
我的问题是为什么 encoding_st 指针与编码指针不同。我试图用几个关键词来寻找原因。但我没有找到类似的问题。:(
您encoded
在 if 语句的范围内重新声明了同名变量
char* encoded;
if(method == 0){
char* encoded = manchester(bitstring); // where the confusion occur
}
else if (method == 1){
char* encoded = differential_manchester(bitstring);
}
因此,encoded
在相对于 if 语句的外部作用域中声明的变量保持未初始化状态。
删除 if 语句中的声明
char* encoded;
if(method == 0){
encoded = manchester(bitstring); // where the confusion occur
}
else if (method == 1){
encoded = differential_manchester(bitstring);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句