gpt4 book ai didi

c - C 初学者 : strings and memory

转载 作者:行者123 更新时间:2023-11-30 18:30:14 24 4
gpt4 key购买 nike

所以我正在做的这门类(class)希望我们尝试内存管理和指针。我还没有完全理解它们。

我不断收到错误:

Segmentation fault (Core dumped)

显然我无权访问内存?

我的 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


}

最佳答案

问题不在您的 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);

关于c - C 初学者 : strings and memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com