【发布时间】:2015-08-18 16:10:24
【问题描述】:
所以我正在做的这门课程希望我们玩弄内存管理和指针。我并没有完全理解它们。
我不断收到错误:
分段错误(核心转储)
显然我无法访问内存?
我的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
}
【问题讨论】:
-
这里至少有一个提示:当您将 msg 交给 scanf 时,您希望它指向什么?
-
在 C 中,当调用 malloc() 和函数族时。返回值为 void*。 void 指针可以分配给任何其他指针,因此不要强制转换返回值。表达式 'sizeof(char)' 定义为 1,因此对传递给 malloc() 的参数没有影响。建议通过删除强制转换和删除“sizeof(char)”表达式来整理代码。
-
关于这一行:'char *msg = NULL;' 'msg' 指向地址 0,不允许用户程序访问/写入。建议使用“readline()”或其他方法让“msg”指向内存中的某个值位置。