【发布时间】:2021-12-04 23:15:51
【问题描述】:
所以,我遇到了一个我不太了解的问题。请善待我正在尝试自学C!
我有一个名为 secureInput() 的函数,它接受一个指向字符串的指针和一个 size,这样,当用户必须输入一些输入我可以确定没有缓冲区溢出。现在,问题是我想修改字符串而不复制它,而是直接通过它的内存地址修改它,但是当用户输入中的第二个字符被分配时它就会崩溃。查看 cmets 以了解它在哪里崩溃。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int secureInput(char **str, int size);
int main(int argc, const char * argv[]) {
char *mystring = NULL; // Declaring it a null so that I use malloc later
secureInput(&mystring, 10);
printf("%s\n", mystring);
}
int secureInput(char **str, int size)
{
*str = (char*)malloc(sizeof(char) *size); // Because **str is a null pointer, I use malloc to allocate memory.
if (*str == NULL)
return -1;
int c = 0;
unsigned int count = 0;
while((c = getchar()) != '\n' && count < size)
/* Here is where it crashes.
* But changing the bellow line as : *str[0][count++] = c;
* works as expected. Also, using a temporary pointer
* and later using it to replace *str, is also working
*/
*str[count++] = c;
*str[count] = '\0';
return 0;
}
【问题讨论】:
-
将
*str[count++]更改为(*str)[count++]和另一个。 -
您的
str[count]从传递给函数的指针获取偏移量,而不是从分配的指针获取。然后*取消引用非法指针。通过返回指针(或NULL)而不是通过参数来编写函数会更容易。 -
@Liwinux 都是关于优先规则的!您可以将其与数学优先级进行比较。在 C 中,数组下标优先于指针的取消引用(请参阅此处的列表:en.cppreference.com/w/c/language/operator_precedence)。
-
这可以通过使用局部变量 (
char *s = malloc(); *str = s;) 来简化一点,然后在函数的其余部分使用s。这也会使错误处理更容易一些(直到最后才分配给*str),因为在您知道自己完成之前不会对调用者的数据进行任何更改。 -
另请注意,
(*str)[count]可能会访问超过分配空间的末尾。您应该分配一个额外的字节或少读一个字符。
标签: c malloc pass-by-reference