首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用C语言实现多文件项目中的动态内存分配

用C语言实现多文件项目中的动态内存分配
EN

Stack Overflow用户
提问于 2012-11-26 17:37:14
回答 1查看 466关注 0票数 0

我被要求实现一个与string.h库类似的库。然而,我不允许在我的库中使用'\0'来结束我的字符串;这就是为什么我应该在我的程序中使用字符串的结构。我在mystring.h文件中有这个:

代码语言:javascript
复制
#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文件中有这个:

代码语言:javascript
复制
#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文件中有以下内容:

代码语言:javascript
复制
#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工作正常,但我在返回时发生了崩溃。有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-26 17:41:59

ns在被解除引用时是一个未初始化的指针:

代码语言:javascript
复制
mystring_t ns;

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

因为mystring_tstruct cell*typedef。在使用之前为ns分配内存:

代码语言:javascript
复制
mystring_t ns = malloc(sizeof(*ns)); /* No cast on return value required. */
if (ns)
{
    ns->string = calloc(MAXSTRLEN, 1);
    ns->length = 0;
}

顺便说一句,这是我不喜欢在typedef__s中隐藏指针的原因之一,因为它在使用时并不明显。

while循环的情况下,保护超出ns->string的界限。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13562052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档