【问题标题】:Why it caused SIGSEGV (signal 11) (core dumped)?为什么会导致 SIGSEGV(信号 11)(核心转储)?
【发布时间】:2020-08-31 23:10:10
【问题描述】:

这里我有一个函数,它从 struct 中获取一个字符串数组并返回 struct integer_array。

#include "string.h"
#include "stdlib.h"
integer_array* my_count_on_it(string_array *p1)
{
    integer_array *pusher;
    int size = p1->size;
    char** str = p1->array;
    pusher = (integer_array*) malloc(size*sizeof(integer_array));

    for (int i = 0;i<size;i++)
    {
        pusher->array[i] = strlen(str[i]);
    }
    return pusher;
}

函数原型(c):

  typedef struct s_string_array {
    int size;
    char** array;
  } string_array;

 typedef struct s_integer_array {
   int size;
   int* array;
 } integer_array;

@param {string_array*} param_1
@return {integer_array*}


integer_array* my_count_on_it(string_array* param_1) {

}


这就是它应该如何工作

输入/返回示例:

输入: ["This", "is", "the", "way"]
返回值: [4, 2, 3, 3 ]

输入: ["aBc"]
返回值: [3]


【问题讨论】:

  • 欢迎来到 Stack Overflow。请尽快阅读About 页面并访问描述How to Ask a QuestionHow to create a Minimal, Complete, and Verifiable example 的链接。提供必要的详细信息,包括您的代码、编译器警告和相关错误(如果有),将允许这里的每个人帮助您解决问题。 (也就是说——我的水晶球怀疑你在p1-&gt;array 中有未初始化的指针,这样strlen(str[i]); 陨石坑......)
  • 如何调用my_count_on_it()。传入了什么,调用者如何定义和初始化/设置?
  • 重点是,没有A Minimal, Complete, and Verifiable Example (MCVE),我们只能猜测。您发布的内容本质上没有任何错误(或正确)。
  • 老实说,在您的应用程序崩溃后看到(core dumped) 真是太棒了!这意味着操作系统已经创建了一个核心文件,您可以使用调试器打开该文件并查看源代码中发生崩溃的位置。这是您学习如何分析这样一个核心文件的绝佳机会,这对您将来无疑会有所帮助。
  • 函数 `my_count_on_it' 实际上被定义了两次,这可能导致实现被覆盖。你不应该对原型使用大括号。

标签: c arrays function runtime-error structure


【解决方案1】:

integer_array *pusher 初始化良好。但是其中的各个指针也应该被初始化。您可能想要这样做 pusher-&gt;array = (int*) malloc(sizeof(int) *size) 。但老实说,我并没有掌握你想用那个函数调用实现什么。您声明了一个 integer_array 数组,但您似乎只使用了第一个元素,我怀疑它们是您代码中的潜在逻辑错误。

编辑:正如@David C. Rankin 提到的,也可能是您没有为p1-&gt;array 分配有效值

您可能希望拥有这样的功能。

#include "string.h"
#include "stdlib.h"
#include "stdio.h"

typedef struct s_string_array {
    int size;
    char** array;
} string_array;

typedef struct s_integer_array {
    int size;
    int* array;
} integer_array;

integer_array* my_count_on_it(string_array *p1)
{

    integer_array* pusher = (integer_array*) malloc(sizeof(integer_array));

    pusher->size = p1->size;
    pusher->array = (int*) malloc(sizeof(int) * p1->size);

    for (int i = 0; i < p1->size; i++)
    {
        pusher->array[i] = strlen(p1->array[i]);
    }
    return pusher;
}

int main()
{
    string_array *p1 = NULL;

    /* collect data from user */

        // Setup p1{} struct

    integer_array* pusher = my_count_on_it(p1);

    for (int i = 0; i < pusher->size ; i++)
        printf(" %d ", pusher->array[i]);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多