下記のC言語のプログラムをgccでコンパイルして実行すると、最初のprintf関数
が実行される前に
*** Error in `./a.out': realloc(): invalid pointer: 0x00007ffcd822789f ***
が行頭の長いエラーメッセージのようなものが出て強制終了してしまいます。
C
1#include <stdio.h> 2#include <stdlib.h> 3 4typedef struct{ 5 char name[64]; 6 int age; 7 int sex; 8} person; 9 10int main(void){ 11 int count = 1; 12 person *persons; 13 14 while(1){ 15 person per; 16 per.age = count + 10; 17 if(4 < count){ 18 break; 19 } 20 persons = (person*)realloc(persons, sizeof(person) * count); 21 persons[count - 1] = per; 22 printf("No.%d age is %d", count, persons[0].age); 23 count+=1; 24 } 25 return 0; 26}
realloc関数の部分は同じなのに、このプログラムだとエラーは出ずに実行できる。
C
1#include <stdio.h> 2#include <stdlib.h> 3 4typedef struct{ 5 char name[64]; 6 int age; 7 int sex; 8} person; 9 10int main(void){ 11 int count = 1; 12 person *persons; 13 persons = (person*)realloc(persons, sizeof(person) * count); 14 15 return 0; 16}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/16 04:32 編集
2018/02/16 04:38 編集
2018/02/16 07:27