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一个typedeffor 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,这是我不喜欢在typedefs 中隐藏指针的原因之一,因为它在使用时并不明显。

在循环ns->string条件下保护越界。while

于 2012-11-26T09:41:59.197 回答