简体   繁体   English

分段错误:循环打印时为11

[英]Segmentation fault: 11 when printing out of a loop

First of all say that I have been looking for information on the network, making tests with gdb debugging and...nothing...I still do not understand the error, I get the idea that it might come from the "getline" instruction, but I'm not sure... 首先要说的是,我一直在寻找网络上的信息,使用gdb调试进行测试……什么也没有...我仍然不理解该错误,我认为它可能来自“ getline”指令,但我不确定...

The main idea of the code is to read line by line and convert chars strings into floats and save the floats in a array called nfloat and then call the function: *create_table* to create an array of pointers of type vector. 该代码的主要思想是逐行读取并将char字符串转换为浮点数,然后将浮点数保存在名为nfloat的数组中,然后调用函数:* create_table *以创建类型为vector的指针数组。

The input is a .txt containing this: n = the number of strings, in this case n = 3 输入是一个包含以下内容的.txtn =字符串数,在这种情况下, n = 3

3
[9.3,1.2,87.9]
[1.0,1.0]
[0.0,0.0,1.0]

The first number, 3 is the number of vectors as we can see in the image, but that number isn't static, the input can be 5 or 7 , etc instead of 3 . 第一个数字3是我们在图像中看到的向量数量,但是该数量不是静态的,输入可以是57 ,以此类推而不是3

So far, I've started doing the following, but the code has some memory errors I think: 到目前为止,我已经开始执行以下操作,但是代码中存在一些我认为的内存错误:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct {
    float* data;
    int size;
} vector;




vector *create_vector(int n, float* comps){
    vector newvect;
    newvect.data = (float *) malloc(n*sizeof(float));
    int i;
    for(i = 0; i < n; i++) {
        newvect.data[i] = comps[i];
        printf("Newvec.data[%d] = %.1f\n", i, newvect.data[i]);
    }
    newvect.size = n;
    vector *pointvector;
    pointvector = &newvect;
    return(pointvector);
}


int NumsVector(char *linea, ssize_t size){
    int numsvector = 1; 
    int n;
    for(n = 2; n<= size; n++){ 
        if (linea[n] != '[' && linea[n] != ']'){
            if(linea[n] == 44){
                numsvector = numsvector + 1;
            }
        }
    }
    return numsvector;
}

int main(){
    int n, i;
    scanf("%d\n", &n);
    vector *v[n];
    for(i = 0; i<n; ++i) { 
        char *line = NULL; 
        size_t len = 0;
        ssize_t read; 
        read = getline(&line,&len,stdin);
        int numsvector = NumsVector(line, read);
        float nfloat[numsvector];
        int j = 0;
        /* Replaces the end ] with a , */
        line[strlen(line) - 1] = ',';

        /* creates a new pointer, pointing after the first [ in the original string */
        char *p = line + 1;
        do
        {
            /* grabs up to the next comma as a float */
            sscanf(p, "%f,", &nfloat[j]);
            /* moves pointer forward to next comma */
            while (*(p++) != ',');
        }
        while (++j < numsvector); /* stops when you've got the expected number */
        v[i] = create_vector(numsvector, nfloat);
        printf("%f\n", v[i]->data[1]); //prints ok :)!
        free(line);
    }
    printf("%f\n", v[i]->data[1]); //segmentation fault:11 :(!! }

Well, the problems come with the printf instructions I think, when I print inside the loop, everything works fine but when I try to do the same out of the for loop, it prints the segmentation fault error...might be some memory leak? 好吧,问题与我认为的printf指令有关,当我在循环内打印时,一切正常,但是当我尝试在for循环中执行相同操作时,它会打印分段错误错误...可能是内存泄漏?

is important for me to know if *v[n] is well implemented and stores well the information in order to keep creating functions based on the *v[n] information. 对于我来说,了解* v [n]是否得到了很好的实现并很好地存储了信息非常重要,以便继续基于* v [n]信息创建函数。

Please could someone help me understand where is the problem when I print out the loop? 请问有人可以帮助我了解打印循环时问题出在哪里吗?

vector *pointvector;
pointvector = &newvect;
return(pointvector);

You're returning pointer to local variable. 您正在返回指向局部变量的指针。 This is incorrect and needs to be changed either by allocating dynamic memory for newvect or by using static variable within function and then copying data (data wouldn't persist between two calls). 这是不正确的,需要通过为newvect分配动态内存或通过在函数内使用static变量然后复制数据(两次调用之间的数据不会持久)来更改。

Edit: as requested, example with dynamic allocation: 编辑:根据要求,动态分配示例:

vector *create_vector(int n, float* comps){
    vector *newvect = malloc(sizeof(*newvect));
    newvect->data = malloc(n*sizeof(float));
    memcpy(newvect->data, comps, sizeof(float) * n);
    newvect->size = n;
    return newvector;
}

Of course at some point you'll need to free both data and vector itself. 当然,在某些时候,您将需要释放数据和向量本身。

In this line 在这条线

printf("%f\n", v[i]->data[1]); //segmentation fault:11 :(!! }

i equals n . i等于n And as v is declared v[n] the above line provokes undefined behaviour by accessing v out of bounds. v被声明为v[n] ,上述行通过超出范围访问v引发了未定义的行为。


To get around the issue of returning an address to a local variable do like this: 要解决将地址返回到局部变量的问题,请执行以下操作:

vector * create_vector(size_t n, float * comps)
{
  vector * newvect = malloc(sizeof(*newvect);
  if (NULL != newvect)
  {
    return NULL;
  }

  newvect->data =  malloc(n * sizeof(*newvect->data));
  if (NULL != newvect->data)
  {
    free(newvect);
    return NULL;
  }

  for(size_t i = 0; i < n; i++) 
  {
    newvect->data[i] = comps[i];
    printf("newvect->data[%zu] = %.1f\n", i, newvect->data[i]);
  }

  newvect->size = n;

  return newvect;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM