条目数为6或10时发生错误

问题描述 投票:0回答:1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE* ip;
FILE* op;

int main(int argv,char* args[]) {
    ip = fopen(args[1],"r");
    op = fopen(args[2],"wr");

    char *line;
    size_t len = 0;
    len = getline(&line,&len,ip);
    int arr_index = 0;
    int *arr = malloc(sizeof(int)*((len-1)/2));

    char *ptr = strtok(line, " ");
    while(ptr != NULL){
        arr[arr_index++] = atoi(ptr);
        ptr = strtok(NULL," "); //line대신 NULL
    }
    for(int i=0 ; arr[i] ; i++){
        printf("%d ",arr[i]);
    }
//Do not use sizeof() (Because this is the part of my code. Later I need to size this way instead of using 'sizeof'.
}

它可以用其他数字正常工作,但是当它是6或10时只会发生错误。(测试1到30)

输入:“ 1 2 3 4 5 6”->输出:“ 1 2 3 4 5 6 1041

输入:“ 1 2 3 4 5 6”->输出:lab9:malloc.c:2401:sysmalloc:声明`(old_top == initial_top(av)&& old_size == 0)|| (((unsigned long)(old_size)> = MINSIZE && prev_inuse(old_top)&&(((unsigned long)old_end&(pagesize-1))== 0)'失败。

输入:“ 1 2 3 4 5 6 7 8 9 10”->输出:“ 1 2 3 4 5 6 7 8 9 10 1041

输入:“ 1 2 3 4 5 6 7 8 9 10”->输出:“ 1 2 3 4 5 6 7 8 9 10”

c getline strtok
1个回答
1
投票

getline()要求line指针是指向分配的缓冲区或NULL的指针,以便在缓冲区不够大时可以调用realloc()。您从未初始化过line,因此它使用未初始化的值调用realloc(),这会导致未定义的行为。将声明更改为:

int *line = NULL;

[当lineNULL时,getline()将为其分配必要的内存。

© www.soinside.com 2019 - 2024. All rights reserved.