4

さて、このコードを実行すると、セグメンテーション エラーが発生します。

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
#define MAX 64

struct example {
    char *name;
};

int main()
{
    struct example *s = malloc (MAX); 
    strcpy(s->name ,"Hello World!!");
    return !printf("%s\n", s->name);
}

端末出力:

alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ make q1
cc -Wall -g    q1.c   -o q1
alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ ./q1
Segmentation fault (core dumped)
alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ gedit q1.c

誰かが何が起こっているのか説明できますか?

4

4 に答える 4

3

構造体にメモリを割り当てた可能性がありますが、その文字ポインタには割り当てていません。

割り当てられていないメモリに対して strcpy を実行することはできません。あなたは言えた

s->name = "Hello World"; 

代わりは。

または、char にメモリを割り当ててから、コピーを実行します。 : 次のコードが適切であることを保証するものではありません。動作することだけを保証します。

int main()
{
  struct example *s = malloc(MAX);
  s->name = malloc(MAX);
  strcpy(s->name ,"Hello World!!");
  return !printf("%s\n", s->name);
}

編集:これはおそらくよりクリーンな実装ですが、私はまだCスタイルの文字列が嫌いです

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define KNOWN_GOOD_BUFFER_SIZE 64

typedef struct example {
  char *name;
} MyExample;

int main()
{
  MyExample *s = (MyExample*) malloc( sizeof(MyExample) );
  s->name = (char*) malloc(KNOWN_GOOD_BUFFER_SIZE);
  strcpy(s->name ,"Hello World!!");
  printf("%s\n", s->name);
  free(s->name);
  free(s);
  return 0;
}
于 2013-10-29T03:42:35.687 に答える
1

構造体にメモリを割り当てていますが、char *name はまだ初期化されていないメモリを指しています。char * にもメモリを割り当てる必要があります。作成後に変更できる最大サイズ 64 の文字列にしたい場合は、次のようにします。

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
#define MAX 64

struct example {
    char *name;
};

int main()
{
    struct example *s = malloc(sizeof(struct example)); 
    s->name = malloc(MAX * sizeof(char));
    strcpy(s->name ,"Hello World!!");
    return !printf("%s\n", s->name);
}

MAX を char * のみに割り当てていることに注意してください。例の構造体は sizeof(struct example)) だけあればいいので、MAX にしても意味がありません。サンプル構造体のメンバーを変更しても、malloc が正確なサイズを提供し続けるため、これはより良いアプローチです。

于 2013-10-29T03:52:51.913 に答える
0
struct example *s = malloc (MAX); 

その行は、64 のサンプル構造を保持できるメモリを指しています。各例の構造体には、ポインター (名前と呼ばれる) を保持するのに十分なメモリしかありません。

strcpy(s->name ,"Hello World!!");

s->name はどこも指していないため、有効ではありません。割り当てられたメモリを指す必要があります。

あなたはおそらく欲しい:

struct example *s = malloc(sizeof(struct example)); //Allocate one example structure
s->name = malloc(MAX); //allocate 64 bytes for name 
strcpy(s->name,"Hello world!"); //This is ok now.

これは次と同じです。

struct example s;  //Declare example structure
s.name = malloc(MAX);  //allocate 64 bytes to name
strcpy(s.name,"Hello world!");
于 2013-10-29T04:00:38.643 に答える