【发布时间】:2020-05-28 13:41:25
【问题描述】:
所以我现在正在练习和学习 C,遇到了来自 CodeWars 的一个相当简单的挑战,要求打印一串“Aa~”、“Pa!”和“Aa!”取决于 n 是否
我想确保通过这些问题了解基础知识
所以我知道在其他带有 int 的 malloc 示例中,我们设置了一个指针(int 类型)来指向分配的内存块。当我声明“char *ptr”指向分配的内存块时,它是否仍然是一个指针,因为请原谅我认为“char *anything”意味着它是表示字符串的约定。因此,如果我没有像我想的那样设置像“char **ptr”这样的指针,那么不确定为什么下面会起作用。
当我尝试返回答案时,尤其是当“val”为 1 或 0 时,为什么会收到“malloc: *** error for object 0x100000fab: pointer being free was not assigned” 类型的错误?我在某处读到将指针(字符串?)答案更改为 NULL 将解决问题,但不完全确定为什么会这样。
3 继续上面的问题,为了释放空间,如果我们在函数中动态分配内存块但需要从该函数返回值,那么最好的方法是什么?例如,我们是在之后还是之前释放空间?
感谢大家的意见。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define val 1
char *sc(int); // function declaration/prototype
int main(int argc, const char * argv[]) {
char *answer = sc(val);
printf("The answer is %s\n", answer);
answer = NULL; // why does this work
free(answer);
return 0;
}
char *sc(int n) {
// if n < 6 then will have an extra "Aa!" after "Pa!" at the nth position
char *ptr = (char*) malloc(n*4);
if (ptr == NULL){
printf("malloc failed");
}
char *first = "Aa~ ";
char *second = "Pa! Aa!";
char *third = "Pa!";
if (n <= 6 && n >1) {
for (int i = 0; i <n-1; i++){
ptr = strcat(ptr, first);
}
ptr = strcat(ptr, second);
}
else if (n> 6){
for (int i = 1; i < n; i++) {
ptr = strcat(ptr, first);
}
ptr = strcat(ptr, third);
}
else if (n <= 1){
ptr = "";
}
else {
printf("Error!");
exit(0);
}
return ptr;
}
【问题讨论】:
-
answer = NULL; // why does this work-- 没有。它可能看起来有效,但它后面的行不会做任何事情,因为您的指针不再指向原始内存。很可能你那里有内存泄漏。 -
鉴于
char *ptr = (char*) malloc(n*4);,当此函数的调用者在其返回的指针上调用free()时,ptr = ""既是内存泄漏,也是内存损坏的可能来源。 -
strcat(ptr, first);导致未定义的行为。strcat()要求参数为以 null 结尾的字符串,但您从未在分配后初始化ptr指向的内存。 -
ptr = strcat(ptr, second);在我看来像是缓冲区溢出。 -
如果你不使用
argc和argv,不要声明它们。