c - C程序中的段错误(核心转储)错误

标签 c gcc

我尝试使用适用于 Linux 的 gcc 编译器编译并运行以下程序来反转字符串,但它显示错误:段错误(核心已转储)。我什至尝试使用 gdb 进行调试,但没有帮助。下面给出的程序首先输入 t,它是测试用例的数量。我用 3 个测试用例测试了程序,但是在从用户那里获取第二个输入后,编译器显示错误。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strrev(char*);

int main(int argc, char *argv[])
{
        int t,i=0,temp=0;
        char *str[10],*rev[10];
        scanf("%d",&t); //input the number of test cases
        while(i<t)
        {
            scanf("%s",str[i]);
            i++;
        }
        while(temp<t) //reverse the string and display it
        {
           rev[temp]=strrev(str[temp]);
           printf("%s \n",rev[temp]);
           temp++;
        }
    return 0;
    getchar();
}

反转字符串的函数:

char *strrev(char *str) 
{

    int i = strlen(str)-1,j=0;

    char ch;
    while(i>j)
    {
        ch = str[i];
        str[i]= str[j];
        str[j] = ch;
        i--;
        j++;
    }
    return str;
} 

最佳答案

您遇到段错误是因为您没有为 str 的元素分配空间。 您需要先在 main 函数中分配内存。

scanf("%d",&t); //input the number of test cases

if(t <= 10)
    for(size_t i = 0; i < t; i++)
        str[i] = malloc(50); // Assuming string is no more than 50characters. 
else  
    exit(0);  

除此之外,您的代码中还有许多缺陷。这是修复它们后的代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void strrev(char*);  // Change return type to void

int main(void)
{
    int t,i=0,temp=0, ch;
    char *str[10];
    scanf("%d",&t); //input the number of test cases
    while((ch = getchar()) != EOF && ch != '\n'); // To consume newline character after scanf

    // Allocate memory for str elements
    if(t <= 10)
        for(size_t i = 0; i < t; i++)
            str[i] = malloc(50); // Assuming string is no more than 50characters.
    else
        exit(0);

    i = 0;
    while(i < t)
    {
        fgets(str[i],50,stdin); // Use fgets instead of scanf to read string
        i++;
    }
    while(temp<t) //reverse the string and display it
    {
        // Since you are reversing string by flipping the characters the same 
        // string just pass pointer to it. str[temp] will be updated in function.
        strrev(str[temp]);
        printf("Reverse is %s \n", str[temp]);
        temp++;
    }
    return 0;
}

void strrev(char *str)
{

    size_t i = strlen(str)-1,j=0;
    char ch;
    while(i>j)
    {
        ch = str[i];
        str[i]= str[j];
        str[j] = ch;
        i--;
        j++;
    }
    //printf("Reverse is %s \n", str);
}

关于c - C程序中的段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34440921/

相关文章:

整数数组的 C While 循环

c++ - 如何使用 objdump 在高度优化的目标文件中交错源代码?

C++11 Code::Blocks GCC 在编译依赖成员结构的可变参数模板时崩溃

c - 为什么会出现 C malloc 断言失败?

c - 使用 C 编程的 scanf() 后不显示输出

c++ - 运行程序时出现运行时错误,但使用调试器时却没有

c - 结构数组初始化中的 MISRA-C 错误

C 目录遍历 - 打印不应该的目录名称

c++ - 如何正确地将 OpenCV 库链接到 Windows 上的 Eclipse?

Linux/gcc - 我应该如何编译我的程序以使用安装在我的主目录中的库?