简体   繁体   English

在C中返回数组:随机错误,垃圾值

[英]Returning array in C: random errors, garbage values

I'm trying to get this to work but I keep getting really weird errors, sometimes it executes without error, sometimes I get memory access violation errors, 7 of the returned values are always garbage and there's a printf that the program won't work with for some reason. 我正在尝试使其正常工作,但我一直收到非常奇怪的错误,有时它执行时没有错误,有时我遇到memory access violation错误,其中7个返回值始终是garbage并且有一个printf表示程序无法正常工作由于某种原因。 I'm not good with C so I haven't the slightest clue what is going on. 我对C不好,所以我丝毫不知道发生了什么。

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

int gen_bp() {
  int min = 0;
  int max = 3;
  int r;
  r = (rand() % (max + 1 - min)) + min;
  return r;
}

int * gen_gene(int len) {
  int a;
  int * gene = malloc(len);
  int bp;
  srand( (unsigned)time( NULL ) );
  for( a = 0; a < len; a = a + 1 ){
    bp = gen_bp();
    printf("value of a: %i\n", bp); //if i remove this line, it crashes?!
    gene[a] = bp;
  }
  return gene;
}

int main()
{
  char codons[4] = {'G','T','A','C'};
  int genelen = 20;
  int counter;
  int * gene;
  gene = gen_gene(genelen);
  for( counter = 0; counter < genelen; counter++ ){
    printf("%i value of a: %i\n", counter, gene[counter]);
  }
  free(gene);
  return(0);
}

This is the output I get 这是我得到的输出

value of a: 1
value of a: 1
value of a: 3
value of a: 0
value of a: 2
value of a: 1
value of a: 3
value of a: 3
value of a: 1
value of a: 2
value of a: 3
value of a: 0
value of a: 3
value of a: 1
value of a: 0
value of a: 2
value of a: 3
value of a: 2
value of a: 2
value of a: 0
0 value of a: 1
1 value of a: 1
2 value of a: 3
3 value of a: 0
4 value of a: 2
5 value of a: 1
6 value of a: 3
7 value of a: 3
8 value of a: 1
9 value of a: 2
10 value of a: 1635131449 // 10 to 16 are always garbage, and never change
11 value of a: 1702194273
12 value of a: 543584032
13 value of a: 891304545
14 value of a: 808661305
15 value of a: 892351281
16 value of a: 2570
17 value of a: 2
18 value of a: 2
19 value of a: 0

Sometimes it ends fine with 0 error, other times it crashes after the output. 有时它以0错误结束,而有时它在输出后崩溃。 Absolutely not the slightest clue why. 绝对没有丝毫的线索。

You are reserving space for len bytes, but you want to reserve space for 您正在为len个字节保留空间,但您想为

int * gene = malloc(sizeof(int) * len);

or 要么

int * gene = malloc(sizeof(*gene) * len);

And you forget to #include <time.h> 而且您忘记了#include <time.h>

Using malloc directly is too error-prone; 直接使用malloc容易出错。 in your code you forgot to multiply with the element size. 在代码中,您忘记与元素大小相乘。

Use a macro instead: 改用宏:

#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof (ptr)[0])

int *gene;
NEW_ARRAY(gene, len);

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

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