调用函数时出现分段错误

当我调用 print_linklist 函数时,出现分段错误。下面是函数定义:

//will display the node in a nice string
char * term_to_string(term_t * term){
    int exp = term->exponent;
    int coef = term->coefficient;
    return ("%dx^%d", coef, exp);
}

**//will print the list using the nodde_to_string method
void print_linklist(node_t * curr){
    printf("entering print to list!!!");
    node_t * current = curr;
    while(current != NULL){
        printf("%s +", term_to_string(curr->term));
        current = current->next_node;
    }
}**

这是调用它的主要方法:

/* This is your main file */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"common.h"
#include"buildlinklist.h"
#include"printandcombine.h"
int main() {
    node_t * node_ptr = NULL;
    node_t * new_node_ptr=NULL;
    printf("NAME: SAMPLE OUTPUTn");
    
    /* Build linklist */
    read_objects(&node_ptr);
    
    /* Print the link list */
    printf("Original: n");
    print_linklist(node_ptr);
    
    /* Combine like terms in the link list and craeate a new link list */
    new_node_ptr=combine_like_terms(node_ptr);
    printf("nCombined: : ");
    /* Print new combine linklist */
    print_linklist(new_node_ptr);
    printf("nNAME: SAMPLE OUTPUTn");
    free(node_ptr);
    free(new_node_ptr);
    return 0;
}

调用该函数后,我得到“zsh:segmentation fault ./project1”。我什至没有得到“输入打印列表!!!” 从 print_linklist 方法打印。

回答

return ("%dx^%d", coef, exp);

这并没有做你认为它在做的事情(我认为你认为它正在做的是返回由某种printf功能创建的字符串)。

但是,类似的逗号运算符a, b同时计算ab,但结果b。该n-variant一样a, b, c, d,评估一切,回到最后一个(d)。

因此,您exp就像是一个字符指针一样返回。几乎可以肯定它不是(因为你试图printf%d)所以,如果你这样对待它,可能会带来欢笑。

好吧,更少的欢闹和更多的崩溃/怪异,但你明白了:-)


可以在堆内存中创建字符串并传递它们,但是对于语言的新手来说,有时很难安全地做到这一点。相反,我建议简单地函数中打印内容,例如:

void print_term(const term_t *term, const char *after){
    printf("%dx^%d%s", term->coefficient, term->exponent, after);
}

void print_linklist(node_t *curr){
    puts("entering print to list!!!");
    node_t *current = curr;
    while (current != NULL){
        print_term(curr->term, " +");
        current = current->next_node;
    }
}

您会注意到我的“输入打印到列表”语句与您的语句略有不同,因为它使用puts,在末尾附加一个换行符(n如果您想坚持使用,您可以使用 明确地这样做printf)。

由于标准输出是针对终端设备进行行缓冲的,因此您看不到的原因几乎可以肯定是由于您的代码在刷新之前崩溃了(根据此答案)。在这种情况下,未刷新的数据很可能会消失。

  • 在 C 中,您甚至不能从返回 `char*` 的函数中返回 `int`。编译器将给出一条诊断消息,指出语言约束违规。如果尽管有该消息,您还是得到了一些二进制可执行文件,那么它所做的一切都将被取消,因为它不是用有效的 C 编写的。

以上是调用函数时出现分段错误的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>