C函数输入以某种方式在地址中占用相同的内存

时间:2017-03-15 06:24:52

标签: c pointers memory-address dereference

我一直盯着这个问题一段时间,我似乎无法找到一个明显的解决方案,也无法找到描述具体问题的词汇。我会尽我所能:

#include <stdio.h>
#include <malloc.h>
#include <string.h>

char** findWords(char** words, int wordsSize, int* returnSize) {

    *returnSize = 15; //<- wordsSize and returnSize have the same memory address????

    printf("wordsSize is %d\n", wordsSize);
    for(int i=0; i<wordsSize; i++)
    {
        printf("i: %d first word: %s, len: %d\n", i, words[i], strlen(words[i]));
    }
}

int main(void){
    char **test; // this should be const char but func decl is predefined

    test[0] = "Hello";
    test[1] = "Alaska";
    test[2] = "Dad";
    test[3] = "Peace";


    int *foo;

    findWords(test, 4, foo);

    printf("%d", *foo);

}

当调用findWords()时,我发现&amp; wordsSize和* returnSize是相同的(即它们具有相同的内存地址)

[New Thread 3492.0x9d0]

Breakpoint 1, findWords (words=0x7efde000, wordsSize=4, returnSize=0x28ff24) at keyboardrow.c:15
15          printf("wordsSize is %d\n", wordsSize);
(gdb) print &wordsSize
$1 = (int *) 0x28ff24
(gdb) print returnSize
$2 = (int *) 0x28ff24
(gdb)

我错过了一些明显的东西吗?在我看来,&amp; wordsSize和returnSize应该有不同的内存地址,因为它们是两个独立的变量。

3 个答案:

答案 0 :(得分:2)

char **test; // this should be const char but func decl is predefined

test[0] = "Hello";
test[1] = "Alaska";
test[2] = "Dad";
test[3] = "Peace";

你不能做你上面做的事情。 test并未指出任何“有意义”的地方。

答案 1 :(得分:1)

问题是

test[0] = "Hello";
test[1] = "Alaska";
test[2] = "Dad";
test[3] = "Peace";

所有这些调用undefined behavior,如test,它本身并不指向有效的内存。

在取消引用test以获取test[n]之前,您需要确保test指向一个有足够大小的有效内存来生成test[n]访问有效的。

您可以简单地编写

,而不是上面的代码段
 char * test[] = { "Hello", "Alaska", "Dad", "Peace" };

并完成它。

答案 2 :(得分:0)

由于您通过调用不指向任何地方的指针来调用未定义的行为,因此各种变量/指针可能指向相同的内存地址,就像在不同变量可能包含相同垃圾值的情况下一样!