如何使用calloc和snprintf

lfapxunr  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(99)

我想使用calloc和snprintf。你能检查我的简单代码,并告诉我如何修复它吗?我一直有一个错误,访问冲突写入位置0xFFFFFFFFB 8A 2D 1F 0。谢谢!

int main()
{
 
    char* buffer1;

    buffer1 = (char*)calloc(1, 14);

    int a = 15;
    int b = 25;
    char c[]="MON"

    int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);

    return 0;
}

字符串
希望能修改一下这个简单的代码。

xqnpmsa8

xqnpmsa81#

这对我来说很有效:

#include <stdio.h>
#include <stdlib.h> // <string.h> not needed

int main(void)
{
    char* buffer1;
    buffer1 = calloc(1, 14); // cast not needed
    if (!buffer1) { fprintf(stderr, "Memory Failure.\n"); exit(EXIT_FAILURE); }

    int a = 15;
    int b = 25;
    char c[4] = "MON";

    int k = snprintf(buffer1, 13, "%02d%02d%s", a, b, c);
    //                    --------------- ^ ---------------
    printf("k is %d; buffer1 has [%s]\n", k, buffer1);

    free(buffer1); // release resources no longer needed

    return 0;
}

字符串
请参阅https://ideone.com/WMtMQt

ruoxqz4g

ruoxqz4g2#

你发布的代码无法编译。

source>:21:5: error: expected ',' or ';' before 'int'
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |     ^~~

字符串
我们来解决这个问题。
尽管如此,固定的代码有许多警告。

<source>: In function 'main':
<source>:21:42: warning: conversion lacks type at end of format [-Wformat=]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                          ^
<source>:21:44: warning: format '%s' expects argument of type 'char *', but argument 5 has type 'int' [-Wformat=]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                           ~^      ~
      |                                            |      |
      |                                            char * int
      |                                           %d
<source>:21:35: warning: too many arguments for format [-Wformat-extra-args]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                   ^~~~~~~~~~~
<source>:21:9: warning: unused variable 'k' [-Wunused-variable]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);


问题是格式字符串中缺少d
始终启用编译器的警告并记住它们。使用gcc,您可以使用-Wall -Wextra -pedantic -Werror

相关问题