0

string.hライブラリに類似したものを実装するように求められました。ただし、'\0'ライブラリ内を使用して文字列を終了することは許可されていません。そのため、プログラムで文字列に構造体を使用することになっています。私はこれをmystring.hファイルに持っています:

#include <stdio.h>
#define MAXSTRLEN 100 // Defining the maximum lenght of the string as being 100

typedef struct scell *mystring_t;
mystring_t makemystring (char cs[]); // This function stores a given string into the mystring structure

私はこれをmystring.cファイルに持っています:

#include <stdlib.h>
#include "mystring.h" // including the header file of mystring library

struct scell {
    char *string;
    int length;
};

mystring_t makemystring (char cs[]){ //Storing a string into the structure

    int i = 0;
    mystring_t ns;

    ns->string=(char*)calloc(MAXSTRLEN ,sizeof(char));

    // printf ("I allocated memory for the string");

    while (cs[i] != '\0')
    {
        printf ("\nI entered into the while\n");
        ns->string[i] = cs[i];
        printf ("I inserted\n");
        i++;
        printf ("I incremented the count\n");
    }
    ns->length=i; // storing the length of the string into the structure
    printf ("%d\n", ns->length);
    printf ("refreshed the length\n");
    printf ("%d", ns->length);
    return ns;
}

私はこれを main.cファイルに持っています:

#include "mystring.h"
#include <stdlib.h>
int main () {

int result;
mystring_t S1;
mystring_t S2;
    // create two strings
S2 = makemystring("Bye");
printf("I got out of the makemystring function\n");
S1 = makemystring("Hi");

これらのprintf()呼び出しは単なるデバッグ ステートメントです。関数 makemystring は正しく動作しているように見えますが、戻るレベルでクラッシュします。誰でも助けてもらえますか?

4

1 に答える 1

3

ns逆参照されると、初期化されていないポインターになります。

mystring_t ns;

ns->string = (char*)calloc(MAXSTRLEN ,sizeof(char));

そのままmystring_tです。typedef_ 使用する前にstruct cell*メモリを割り当てます。ns

mystring_t ns = malloc(sizeof(*ns)); /* No cast on return value required. */
if (ns)
{
    ns->string = calloc(MAXSTRLEN, 1);
    ns->length = 0;
}

FWIW、これはtypedef、使用時に明らかではないため、 s でポインターを非表示にすることを嫌う理由の 1 つです。

ループns->stringの状態で限界を超えて保護します。while

于 2012-11-26T09:41:59.197 に答える