这周刚学了C。我的任务是从用户那里获取一个大整数输入,将其存储到一个struct integer中,并生成一个函数将适当的struct integer输出到标准输出。程序就是这样工作的,但是一旦它给出输出,它就会停止响应。我在编译器中没有发现任何直接错误,也无法找出错误所在。任何其他改进编程风格的建议/技巧也将非常感谢:)

// Header Files Go Here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Function Declarations Go Here
struct integer * convert_integer(char * stringInt);
void printer(struct integer * p);

struct integer {
    int * arr;
    int length;
};

// Main Program
int main() {
    char * x;
    x = (char *) malloc(sizeof(char) * 10000);
    printf("Enter a small string\n");
    scanf("%s",x);
    int j = 0;
    struct integer * book1;
    book1 = convert_integer(x);
    printer(book1);
    return 0;
}

// Function Definitions Go Here
struct integer * convert_integer(char * stringInt) {
    struct integer * x = malloc(sizeof(int) * 100);
    int j = 0;
    while (stringInt[j] != '\0') {
        if (stringInt[j] < 48 || stringInt[j] >= 57) {
            printf("Invalid input. Enter a number ");
            return;
        }
        x->arr[j] = stringInt[j] - 48;
        j++;
    }
    x->length = j;
    printf("\n the length is %d\n", x->length);
    return x;
}

void printer(struct integer * p) {
    int j = 0;
    while (j < p->length) {
        printf("%d", p->arr[j]);
        j++;
    }
}

最佳答案

我添加这个答案是因为NPE不够清楚。
在这个程序中有几个错误,但我认为按一个是在函数convert_integer中。您正在执行以下操作:

struct integer* x= malloc(sizeof(int) * 100);

... 但这是不正确的。考虑到x的数据类型,您为其请求的内存字节太多(这没有什么问题),但是您没有为arr请求内存块。需要如下:
struct integer *x = malloc( sizeof( struct integer ) );

x->arr = malloc( sizeof( int ) * c );

... 其中c是常数(在您的例子中是100?)。请确保当您free此结构时,首先freearr结构,然后free此结构,否则您将发生内存泄漏。
其他我注意到你没有做的事情,总是检查系统调用的结果。您没有检查malloc是否返回了无效的内存块。

关于c - 需要帮助调试C代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18162616/

10-09 01:14
查看更多