Edu*_*sta 1 c valgrind memory-management
这是有问题的代码:
long number = atol(argv[1]);
long prime_limit = number / 2;
int * primes = malloc(sizeof(int) * prime_limit);
long i;
for (i = 2; i <= prime_limit; i++) {
primes[i] = 1; # This is line 16
}
Run Code Online (Sandbox Code Playgroud)
以下是错误:
==9318== Invalid write of size 4
==9318== at 0x40065B: main (003.c:16)
==9318== Address 0x8 is not stack'd, malloc'd or (recently) free'd
==9318==
==9318==
==9318== Process terminating with default action of signal 11 (SIGSEGV)
==9318== Access not within mapped region at address 0x8
==9318== at 0x40065B: main (003.c:16)
==9318== If you believe this happened as a result of a stack
==9318== overflow in your program's main thread (unlikely but
==9318== possible), you can try to increase the size of the
==9318== main thread stack using the --main-stacksize= flag.
==9318== The main thread stack size used in this run was 8388608.
Run Code Online (Sandbox Code Playgroud)
我相信错误必须是我使用malloc的方式,但我不太确定.argv [1]的值是600851475143.
数组0在C中是-origin:
i <= prime_limit;
Run Code Online (Sandbox Code Playgroud)
应该
i < prime_limit;
Run Code Online (Sandbox Code Playgroud)
否则atol不安全,不能进行错误检测.使用strtol一个字符串转换为long.
| 归档时间: |
|
| 查看次数: |
449 次 |
| 最近记录: |