gpt4 book ai didi

c - 共享库段错误;无法弄清楚 valgrind 错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:24 24 4
gpt4 key购买 nike

我是 C 的新手,想创建一个共享库以供学习之用。我在下面有 valgrind 输出(Invalid read of size 8),但我不确定在哪里寻找问题(因此,我无法识别问题所在)。

我的问题是我是否可以让好心人看看并让我知道我哪里出错了。

我的.c文件:

#include <stdio.h>

int mult (int x, int y){
return x * y;
}

void speak (const char* str){
printf("%s\n", str);
}

unsigned char* arr (){
unsigned char* list;

int i;

for (i=0; i<3; i++){
list[i] = i;
}

return list;
}

我的头文件:

int mult (int x, int y);
void speak (const char* str);
unsigned char* arr ();

我的入口点文件:

#include <stdio.h>
#include "xswrap.h"

void main (){
int ret = mult(5, 5);
printf("%d\n", ret);

speak("hello, world!");

unsigned char* list = arr();

int i;

for (i=0; i<3; i++){
printf("%d\n", list[i]);
}
}

我的编译步骤:

gcc -c -fPIC xswrap.c
gcc -shared -fPIC -Wl,-soname,libxswrap.so -o libxswrap.so xswrap.o -lc
gcc -o test main.c -L. -lxswrap

输出:

25
hello, world!
0
1
2
Segmentation fault

Valgrind 输出:

==13410== Memcheck, a memory error detector
==13410== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==13410== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==13410== Command: ./test
==13410==
==13410== Invalid read of size 8
==13410== at 0x4010C13: _dl_fini (dl-fini.c:235)
==13410== by 0x5075FF7: __run_exit_handlers (exit.c:82)
==13410== by 0x5076044: exit (exit.c:104)
==13410== by 0x505C836: (below main) (libc-start.c:325)
==13410== Address 0x620f08 is not stack'd, malloc'd or (recently) free'd
==13410==
==13410==
==13410== Process terminating with default action of signal 11 (SIGSEGV)
==13410== Access not within mapped region at address 0x620F08
==13410== at 0x4010C13: _dl_fini (dl-fini.c:235)
==13410== by 0x5075FF7: __run_exit_handlers (exit.c:82)
==13410== by 0x5076044: exit (exit.c:104)
==13410== by 0x505C836: (below main) (libc-start.c:325)
==13410== If you believe this happened as a result of a stack
==13410== overflow in your program's main thread (unlikely but
==13410== possible), you can try to increase the size of the
==13410== main thread stack using the --main-stacksize= flag.
==13410== The main thread stack size used in this run was 8388608.
==13410==
==13410== HEAP SUMMARY:
==13410== in use at exit: 0 bytes in 0 blocks
==13410== total heap usage: 1 allocs, 1 frees, 4,096 bytes allocated
==13410==
==13410== All heap blocks were freed -- no leaks are possible
==13410==
==13410== For counts of detected and suppressed errors, rerun with: -v
==13410== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault

最佳答案

您永远不会为 unsigned char* list 分配内存,这与您链接共享库这一事实无关。

list 指向一个垃圾地址,先分配它试试:

unsigned char* list = malloc(3);

请注意,当不再需要通过 free(list) 释放时,您必须注意释放。

关于c - 共享库段错误;无法弄清楚 valgrind 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42822394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com