c - 字符串反转程序中的内存问题

标签 c pointers memory

所以我正在尝试编写一个 C 程序,它从命令行接收一个字符串,然后遍历该字符串并使用链表将其反转。它目前不工作,我不确定为什么。到目前为止,我只用 C++ 编程过,所以 C 中的细微差别真的让我陷入困境。谁能帮我找出程序中的错误?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct st_CharNode 
{
char theChar;
struct st_CharNode *next;
} CharNode;


void reverseIt( char *stringbuffer );


int main( int argc, char *argv[] )
{
char *stringBuffer;

//  Check number of user supplied arguments.  
if( argc != 2 )
{
    fprintf( stderr, "usage: %s string.  This reverses the string "
             "given on the command line\n" );
    exit( -1 );
}

// Copy the argument so we can make changes to it
stringBuffer = malloc( strlen(argv[1]) );
strcpy( argv[1], stringBuffer );

// Reverse the string
reverseIt( stringBuffer );

// Print the reversed string
printf( "the reversed string is '%s'\n", *stringBuffer );

return 0;
}


// Build a linked list backwards, then traverse it.

void reverseIt( char *stringbuffer )
{
CharNode *head, *node;
char *scan, *stop;

// initialize local vars
head = node = NULL;

// find the start and end of the string so we can walk it
scan = stringbuffer;
stop = stringbuffer + strlen(stringbuffer) + 1;

// walk the string
while (scan < stop)
{
    if (head == NULL)
    {
        head = malloc( sizeof(CharNode*) );
        head->theChar = *scan;
        head->next = NULL;
    }
    else
    {
        node = malloc( sizeof(CharNode*) );
        node->theChar = *scan;
        node->next = head;
        head = node;
    }
    scan++;
}

// Re-point to the buffer so we can drop the characters
scan = stringbuffer;

//  Traverse the nodes and add them to the string
while( head != NULL )
{
    *scan = head->theChar;
    free( head );
    node = head->next;
    head = node;
    scan++;
}

// Release head
free( head );   
}

当我 ./a.out 并在命令行上输入类似“Hello”的字符串时,我当前的输出是“反转的字符串是‘(null)’”。

最佳答案

仅举几个问题...

分配不足

您没有考虑 C 字符串所需的终止 nulchar。

这个:

stringBuffer = malloc( strlen(argv[1]) );

应该是这样的:

stringBuffer = malloc( strlen(argv[1]) + 1);

复制方向错误

分配后,您立即从新缓冲区复制未初始化的数据,在 argv[1] 顶部进行爆破,直到检测到 nulchar。更多未定义的行为。

这个:

strcpy( argv[1], stringBuffer );

应该是这样的:

strcpy( stringBuffer, argv[1] );

传递给 Printf 的取消引用不正确

"%s" 格式说明符要求将以 nulchar 结尾的字符串的地址 作为匹配的可变参数传递。您正在传递 *stringBuffer,即一个字符值,由编译器提升为 int,然后用作地址。更糟糕的是,因为它是一个可变参数函数,这对于代码 来说是完全合法的,但对于运行 来说显然是未定义的行为。一个好的代码静态分析编译器会为您捕捉到这一点。

这个:

printf( "the reversed string is '%s'\n", *stringBuffer );

应该是这样的:

printf( "the reversed string is '%s'\n", stringBuffer );

所有这些甚至都没有进入实际的反转函数。至少修复这些。您不需要(实际上会很疯狂)使用链表来反转 C 字符串。它可以用两个指针和一个循环(或一个指针和一个索引)来完成,因此剖析该函数似乎适得其反。反转字符串实际上就是这么简单(而且就位):

void reverse_str(char *str)
{
    if (!str || !*str || !*(str+1))
        return;

    char *rhs = str + strlen(str) - 1;
    while (str < rhs)
    {
        char tmp = *str;
        *str++ = *rhs;
        *rhs-- = tmp;
    }
}

关于c - 字符串反转程序中的内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19555891/

相关文章:

带函数和金钱的c指针

java - 在 Java 中分配数组与分配链表时使用了多少内存?

c - 管道设置终端到 gnuplot 管道在屏幕上产生垃圾

检查 stdin 是否有待处理的字节(用于转义序列)

c - Fortran 相当于 C struct malloc/free 用于插件机制

指针取消引用符号 * 可以称为 "many"吗?

c - 为什么 *pointer_name 在一维和二维数组中表现不同

c++ - 在 makefile 之外运行应用程序时出现段错误

c# - 你能通过内存位置而不是内容来比较字符串吗?

c - 如何 "multithread"C代码