我对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
答案 0 :(得分:1)
您永远不会为unsigned char* list
分配内存,这与您链接共享库的事实无关。
list
指向垃圾地址,首先尝试分配它:
unsigned char* list = malloc(3);
请注意,free(list)
不再需要时,必须注意释放。
答案 1 :(得分:1)
为什么不分配列表:
unsigned char* list;
list = malloc(sizeof (unsigned char) * 3);
这将在内存中保留空间以访问list[i]
。