C语言的初学者:字符串和内存

时间:2015-08-18 16:10:25

标签: c memory string

所以我要做的这个课程要我们玩内存管理和指针。我并没有完全理解它们。

我一直收到错误:

  

分段错误(核心转储)

显然我无法访问记忆?

我的slen函数出了什么问题?

/*

In these exercises, you will need to write a series of C functions. Where possible, these functions should be reusable (not use global variables or fixed sized buffers) and robust (they should not behave badly under bad input eg empty, null pointers) .
As well as writing the functions themselves, you must write small programs to test those functions.

- Remember, in C, strings are sequences of characters stored in arrays AND the character sequence is delimited with '\0' (character value 0).

----------------------------------------------------

1) int slen(const char* str)
    which returns the length of string str [slen must not call strlen - directly or indirectly]
*/

#include <stdio.h>
#include <stdlib.h>

/* Returns the length of a given string */
int slen(const char* str) {
    int size = 0;
    while(str[size] != '\0') {
        size++;
    }
    return size;
}

/*
2) char* copystring(const char* str)
    which returns a copy of the string str. [copystring must not call any variant of strcpy or strdup - directly or indirectly]*/
char* copystring(const char* str) {
    int size = slen(str);
    char *copy = (char*) malloc (sizeof(char) * (size + 1));
    copy[size] = '\0';
    printf("before loop");
    int i = 0;
    while (*str != '0') {
        copy[i++] = *str++;
    }
    return copy;
}


int main() {
    char *msg = NULL;
    printf("Enter a string: ");
    scanf("%s", &msg);
    int size = slen(msg);
    //printf("The length of this message is %d.", size);
//  printf("Duplicate is %s.", copystring(msg));

    // Reading from file


}

2 个答案:

答案 0 :(得分:4)

问题不在您的slen功能中,在您使用scanf之前就已经发生了:

  • 您需要为使用scanf
  • 的用户提供的字符串留出一些空间
  • 您不需要将内存缓冲区的地址传递给scanf,该变量已经存有地址。

修改后的代码:

char msg[101];
printf("Enter a string: ");
scanf("%s", msg);
int size = slen(msg);

或者,如果您被要求了解内存分配,请研究malloc的使用情况:

char *msg = malloc(101);
printf("Enter a string: ");
scanf("%s", msg);
int size = slen(msg);

在了解malloc时,不要忘记研究free的相关用法。

此处重要且重要的是管理缓冲区大小:当您为用户扫描的字符串创建内存时,您应该限制实际读。有几种方法可以做到这一点:首先研究scanf格式字符串,您可以在其中使用:

scanf("%100s", msg);

答案 1 :(得分:0)

您需要为msg中的main分配内存 使用char msg[10]或使用malloc。 char *msg = malloc(10*sizeof(char))