2017-05-29 10 views
-1

私はこれを動作させようとしていますが、実際には奇妙なエラーが発生します。エラーが発生しない場合があります。memory access violationエラーが返されます。何らかの理由でプログラムが動作しないprintfがあります。私はCとは良くないので、何が起こっているのか少しでも手掛かりはありません。C:random errors、garbage values

#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); 
} 

これは私が

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 

を取得し、出力は時にはそれが0誤り、それが出力した後にクラッシュし、他の回と罰金終了です。絶対にちょっとした手がかりではない。

+2

あなたは[ 'malloc'](http://en.cppreference.com/w/c/memory/malloc)に渡すサイズが大きそれであることを忘れないでください要素ではなく* bytes *で割り振る必要があります。 –

+0

サイドノート:Cで配列を返すことはできません。ポインタ**を最初の要素**に返します。 – Olaf

答えて

6

あなたはlenバイトのためのスペースを確保しているが、あなたは

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

または

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

のためのスペースを確保したいとあなたが直接mallocを使用し#include <time.h>

+1

コンパイルエラーが発生しましたが、私はちょうど今あなたの誤植を見ました – vonlolzor

+1

今すぐ完璧に動作します!ありがとう! – vonlolzor

+1

@ KeineLustの回答を受け入れる –

0

に忘れてはあまりにもエラー - です易しい;あなたのコードでは要素の大きさを忘れてしまいました。

代わりにマクロを使用します。

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

int *gene; 
NEW_ARRAY(gene, len); 
+1

ああ、それはかなりきれいです、ありがとう! – vonlolzor