以下のコードを実行すると、セグメンテーションフォルトが発生します。これは、回線を削除すると消えます。int i, *ptr[3];
なぜこのようなことが起こっているのか理解できません。これは、すでに問題を招いているなぜ "int i、* ptr [3];"私のコードにセグメンテーションフォルトを生成する?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
enum otype {INT, SYM, CONS};
typedef struct obj {
enum otype type;
struct obj *p[1];
} obj;
int main(void)
{
char *str;
strcpy(str, "test");
printf("%c\n", str[0]);
struct obj obj1;
obj1.type = INT;
obj1.p[0] = (obj*) malloc(sizeof(obj));
obj1.p[0]->type = SYM;
printf("%d\n", (obj1.p[0])->type);
free(obj1.p[0]);
int i, *ptr[3];
return 0;
}
最初のUBは 'strcpy(str、" test ");' 'str'に割り当てられるスペースがありません – yano
あなたの 'str'はポインタですが、メモリは割り当てられていません。次に、 'strcpy'は文字列' 'test"を '' str'が指すところにコピーします。 – Jens