You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

驼峰命名拆分函数返回垃圾值问题排查:已初始化数组仍出现内存访问异常

Fixing Garbage Values in Camel Case Splitting Function

Hey there, let's break down why you're seeing garbage values in your output and fix it step by step!

The Root Cause of Garbage Values

Your main issue is that the dynamically allocated res buffer from malloc is uninitialized. When you call strcat(res, ...), strcat needs to find the null terminator (\0) at the end of the target string to know where to start appending. Since malloc returns memory filled with random bytes, strcat will keep reading past the start of your buffer until it hits a random \0 somewhere in memory—this leads to undefined behavior, including garbage values or even crashes.

Another small problem: using a fixed size of 100 bytes for res is risky. If your input camelCase string is longer than ~99 characters (or has enough uppercase letters to push the total length over 100), you'll get buffer overflow, which also causes unexpected behavior.

Fixed Implementation

Here's a revised version that fixes both issues, with better memory efficiency and safety:

#include <stddef.h>
#include <string.h>
#include <stdlib.h>

// Returned buffer should be dynamically allocated and will be freed by a caller
char* solution(const char *camelCase) {
    // First calculate the total required length
    const size_t original_len = strlen(camelCase);
    size_t space_count = 0;
    
    // Count how many uppercase letters (each needs a preceding space)
    const char *temp_ptr = camelCase;
    while (*temp_ptr) {
        if (*temp_ptr >= 'A' && *temp_ptr <= 'Z') {
            space_count++;
        }
        temp_ptr++;
    }
    
    // Total length = original length + spaces + 1 for null terminator
    const size_t total_length = original_len + space_count + 1;
    char* res = (char*)malloc(total_length);
    
    // Always check if malloc succeeded (returns NULL on failure)
    if (!res) {
        return NULL;
    }
    
    // Build the result string by directly writing characters
    char *res_ptr = res;
    while (*camelCase) {
        if (*camelCase >= 'A' && *camelCase <= 'Z') {
            *res_ptr++ = ' ';
        }
        *res_ptr++ = *camelCase++;
    }
    
    // Don't forget to add the null terminator at the end!
    *res_ptr = '\0';
    
    return res;
}

Key Improvements Explained

  • Pre-calculate required memory: We first count how many spaces we need (one per uppercase letter) to allocate exactly enough memory, avoiding waste or overflow.
  • Direct character writing: Instead of using strcat (which relies on null terminators), we use a pointer to write each character directly into the buffer. This is faster and avoids the uninitialized buffer issue.
  • Malloc success check: Always verify that malloc didn't return NULL—this prevents crashes if memory allocation fails.
  • Explicit null terminator: We manually add \0 at the end to ensure the result is a valid C string.

Why Your Original Temp Arrays Didn't Fix It

You initialized the temp arrays correctly, but that wasn't the problem. The issue was entirely with the res buffer not being initialized to a valid empty string (i.e., starting with \0). Even if you had added res[0] = '\0'; right after malloc, it would have fixed the garbage values—but the fixed implementation above is still better for safety and efficiency.

内容的提问来源于stack exchange,提问作者suchacoolguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:42:38