#include <cstdlib>
#include <cstdio>
main( int argc, char **argv )
{
int *stack = new int[argc];
int it = 0;
while (--argc > 0 )
{
*(++stack) = atoi(*++argv);
printf( "%d \t %d \n", ++it, *stack );
}
delete stack;
return 0;
}
stack[3]
应该包含来自argv[3]
的整数值,但它不包含。
我发现错误与删除操作符munmap_chunk(): invalid pointer
答案 0 :(得分:2)
此代码不是C;这是C ++。您有两种选择:
printf
... <cstdlib>
更改为<stdlib.h>
,将<cstdio>
更改为<stdio.h>
,将new int[argc]
更改为malloc(argc * sizeof *stack);
,将delete stack;
更改为free(stack);
。< / LI>
无论您采用哪种路线,此代码都会调用未定义的行为;它访问stack
超出一个边界,并保留stack
未初始化的第一个元素,我确信这是不可取的。你可能打算在阅读它们之前和递增stack
之前打印这些值,但是由于你错了,你打印的数组中的下一个元素当然还没有分配...
然后最重要的是,你的循环会修改stack
的值(毕竟这是++stack
所做的),以便在你使用delete
时循环之后重新delete
使用new
未创建的引用...您需要确保保留stack
的原始值,该值为delete
d,或者free
d,或其他......
#include <stdlib.h>
#include <stdio.h>
int
main( int argc, char **argv ) {
int *stack = malloc(argc * sizeof *stack);
int it = 0;
while (--argc > 0){
stack[it] = atoi(*++argv);
printf("%d \t %d \n", it, stack[it]);
it++;
}
free(stack);
return 0;
}
答案 1 :(得分:0)
如果您使用数组索引而不是推进指针,那么您的代码将更清晰(并且更正确):
#include <cstdlib>
#include <cstdio>
using namespace std;
main( int argc, char **argv )
{
int *stack = new int[argc];
for( int it = 1; it < argc; ++it )
{
stack[it] = atoi(argv[it]);
printf( "%d \t %d \n", it, stack[it] );
}
delete[] stack;
return 0;
}
不知道为什么你想要使用未使用的stack[0]
。