[英]'Invalid pointer' error with realloc and strcat working on argv
So I basically want my program to be able to save multiple (or in this case, just two) arguments into a string if the program is started with the option -a. 因此,如果程序使用选项-a启动,我基本上希望程序能够将多个(或者在这种情况下,仅两个)参数保存到字符串中。 Here's the code:
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
int main(int argc, char **argv) {
char c;
char *optstr;
int acount = 0;
while( (c = getopt(argc, argv, "a")) != -1) {
switch(c) {
case 'a': acount++; break;
case '?': fprintf(stderr, "wrong opt\n"); exit(1); break;
default: assert(0);
}
}
char *temp;
if(acount == 1) {
optstr = argv[optind];
temp = strdup(optstr);
if(optind+1 < argc) {
temp = realloc(temp, (strlen(temp) + 1 + sizeof(" ")));
temp = strcat(temp, " ");
temp = realloc(temp, (strlen(temp) + 1 + strlen(argv[optind+1])));
temp = strcat(temp, argv[optind+1]);
}
} else {
fprintf(stderr, "too many or not enough a's\n");
exit(1);
}
fprintf(stdout, "%s\n", temp);
return 0;
}
My question lies with the whole realloc business going on. 我的问题在于整个重新分配业务正在进行。 I originally tried the whole thing without the temp variable, and I used optstr instead.
我最初尝试不使用temp变量进行整个操作,而是使用optstr。 Which only gave me "realloc(): invalid pointer" errors.
这只给了我“ realloc():无效的指针”错误。 I'm asking - why is that, and why does it suddenly work with temp?
我在问-这是为什么,为什么它在温度下突然起作用? Is this because optstr's pointer is pointing at an argument in argv, and changing argv would cause errors?
这是因为optstr的指针指向argv中的参数,并且更改argv会导致错误吗? I'm really not sure at all.
我真的不确定。
It's because you don't know how the memory for the strings inside argv
are allocated. 这是因为您不知道
argv
内部字符串的内存分配方式。 You are not supposed to know. 你不应该知道。 They might have been created individually using
malloc
, in which case realloc
will work (but it's not legal), or a large block was malloc
'd and the strings placed within the block, in which case it won't work, or some other variants. 它们可能是使用
malloc
单独创建的,在这种情况下, realloc
可以工作(但不合法),或者malloc
放置了一个大块并将字符串放置在该块中,在这种情况下它将不起作用,或者其他一些原因变体。
When you call realloc
on a pointer from argv
you are claiming that you own that memory; 当您从
argv
的指针上调用realloc
,您声称自己拥有该内存。 this is not true and you are not allowed to reallocate or free it. 这是不正确的,不允许您重新分配或释放它。 See also Memory allocation and **argv argument
另请参阅内存分配和** argv参数
You are only allowed to read the memory, so what you can do, and have done, is use strdup
to create a copy; 只允许您读取内存,因此您可以做的事情是使用
strdup
创建一个副本。 this memory you then do own, so now you are allowed to use realloc
on it. 这种记忆,那么你做自己的,所以现在你被允许使用
realloc
就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.