AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[c](coding)

Martin Hope
ALICEZzz
Asked: 2025-04-29 23:14:59 +0800 CST

块作用域如何工作?标准如何解释这一点?

  • 8

例如我们有这样的代码:

#include <stdio.h>
int main(void)
{
    int n = 4;
    {
        n++;
    }
    printf("%d\n",n);
    return 0;
}

内部代码块如何看待变量 n?C 语言标准对此是如何解释的?我一直在寻找这个问题的答案。在我看来,答案如下:在 C17 中,我们有(6.8 #3):

块允许将一组声明和语句组合成一个语法单元。具有自动存储期的对象的初始化器,以及具有块作用域的普通标识符的变长数组声明器,在每次按声明顺序到达时都会被求值,并将值存储在对象中(包括在没有初始化器的对象中存储不确定的值),就像它是一个语句一样,并且在每个声明中,都按照声明器出现的顺序进行。

如果不考虑初始化器,那么块实际上只是几个语句。我们只是使用一个块将所有这些运算符作为一个语法单元进行评估。换句话说,如果删除块中的 {} 字符,这些将是相同的运算符,结果将完全相同,但这些运算符不会在一个语法单元中进行评估:

#include <stdio.h>
int main(void)
{
    int n = 4;
    
        n++; // same effect but without {}
    
    printf("%d\n",n);
    return 0;
}

我们还有(6.2.1#4):

如果声明标识符的声明符或类型说明符出现在块内或函数定义中的参数声明列表中,则该标识符具有块作用域,该作用域在关联块的末尾终止。

由此我们了解到 n 具有块作用域。

如果我们将以上所有内容结合起来,就会发现 n 会增加,就好像增量运算符从未出现在内部块中一样。

这个答案正确吗?如果不正确,请解释原因。并请引用一段 C 语言标准中的文字。

c
  • 3 个回答
  • 100 Views
Martin Hope
EnzoR
Asked: 2025-04-29 18:15:18 +0800 CST

为什么循环中的内置函数 __sync_or_and_fetch 会呈现为带有 -O2 和 -O3 的无限循环?

  • 6

[已解决]使用__sync_fetch_and_or而不是__sync_or_and_fetch! 双重amoor指令可能仍然是一个错误。

[免责声明] 这可能是 GCC 中的一个错误,但可以肯定的是,我对 RISC-V 汇编还不熟悉!

我正在尝试使用混合 C 语言以及 GCC v14.2.0 和 GCC 15.1.0 的交叉编译,在 RISC-V (64 位,仅供参考) 中实现一个“快速asm()”自旋锁功能。以下代码(非常精简):

#define LOCK_BIT ((unsigned long)(1ul<<(8*sizeof(long)-1)))

void lock_hold(long* lock) {
  while(__sync_or_and_fetch(lock,LOCK_BIT) < 0);
  __sync_synchronize();
}

两个版本均使用-O3和-O2来呈现为:

lock_hold:
    li  a5,-1
    slli    a5,a5,63
.L2:
    amoor.d.aqrl    a4,a5,0(a0)
    amoor.d.aqrl    a4,a5,0(a0)
    j   .L2

这似乎是一个具有两个连续相同amoor指令的无限循环。

首先,我并不期望那里出现无限循环!

如果我切换到-O1,我会得到以下代码:

lock_hold:
    li  a4,-1
    slli    a4,a4,63
.L2:
    amoor.d.aqrl    a5,a4,0(a0)
    or  a5,a5,a4.   #USELESS?
    blt a5,zero,.L2
    fence   rw,rw
    ret

它看起来更像我期望的,同时-Os生成以下代码:

lock_hold:
    li  a5,-1
    slli    a5,a5,63
.L2:
    amoor.d.aqrl    a4,a5,0(a0)
    j   .L2

再次陷入无限循环。

最后,使用-O0我得到的结果与使用的结果基本相同,但-O1有一些额外的说明。

我是不是遇到了 bug,或者遗漏了什么?万一我遗漏了什么呢?

除此之外,我还想得到“比我懂得多得多的人”的回答。

在生成的代码中,-O1我将一条or指令标记为#USELESS?。我是否真的需要对 执行某些操作a5才能在一条amoor写入a5自身的指令之后设置“符号标志”?

万一,这样的事还不够吗or a5,zero,a5?

c
  • 1 个回答
  • 51 Views
Martin Hope
Fayeure
Asked: 2025-04-29 15:42:10 +0800 CST

使用 alloca 在堆栈上分配 const 成员来初始化结构是否有效?

  • 6

考虑到类型A定义如下:

typedef struct a { const int a; } A;

我知道此代码是有效的:

A * foo = malloc(sizeof *foo); // Allocates uninitialized memory with no effective type
memcpy(foo, &(typeof(*foo)){ .a = 42, }, sizeof *foo); // Effectively initialize the value once

(参见https://stackoverflow.com/a/79012045/13242312)

但是,如果我们希望值位于堆栈而不是堆中,alloca那么使用 而不是是否仍然有效?malloc

用例:我希望函数中有一个返回路径,因此我想在函数范围内定义结果变量

A A_new(void) {
  A * a = alloca(sizeof *a);

  if (/* something */) {
    memcpy(a, &(typeof(*a)){.a = 1}, sizeof *a);
  } else {
    memcpy(a, &(typeof(*a)){.a = 2}, sizeof *a);
  }

  return *a;
}
c
  • 1 个回答
  • 66 Views
Martin Hope
Rohan Bari
Asked: 2025-04-29 12:01:32 +0800 CST

为什么在单个语句中调用两个函数不会影响值?[重复]

  • 6
这个问题已经有答案了:
C 语言中函数调用前的参数评估顺序 (7 个答案)
昨天关闭。

在此代码中:

// Stack using LinkedList //

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* top = NULL;

short isEmpty(void) {
    if (top == NULL) {
        printf("error: The stack is empty.\n");
        return 1;
    }
    
    return 0;
}

void push(int value) {
    struct Node* newNode = (void*)malloc(sizeof(struct Node));
    if (!newNode) {
        printf("error: Heap overflow!\n");
        exit(1);
    }
    
    newNode->data = value;
    newNode->next = top;
    top = newNode;
}

int pop(void) {
    if (isEmpty()) {
        exit(1);
    }
    
    struct Node* ref = top;
    int val = top->data;
    top = top->next;
    free(ref);
    
    return val;
}

int peek(void) {
    if (isEmpty()) {
        exit(1);
    }
    
    return top->data;
}

void display(void) {
    if (isEmpty()) {
        exit(1);
    }
    
    while (top) {
        printf("%d\n", top->data);
        top = top->next;
    }
}

int main(void) {
    push(10);
    push(20);
    push(30);
    push(40);
    
    printf("Peek: %d\n", peek());
    int val = pop();
    printf("Popped: %d, now Peek: %d\n", val, peek());
    push(50);
    display();
    
    return 0;
}

看看这些行:

int val = pop();
printf("Popped: %d, now Peek: %d\n", val, peek());

返回:Popped: 40, now Peek: 30

正如预期的那样。但是,当这样写时:

printf("Popped: %d, now Peek: %d\n", pop(), peek());

它产生以下输出:Popped: 40, now Peek: 40

这是Godbolt。

有人能告诉我为什么会这样吗?

c
  • 1 个回答
  • 71 Views
Martin Hope
Ildar
Asked: 2025-04-28 01:21:08 +0800 CST

docker容器中dpdk应用如何拦截容器接口eth0的所有数据包

  • 7

我已经设置了大页面,创建了容器并将 dpdk 应用程序部署到容器中,但我的应用程序返回 0 rte_eth_dev_count_avail,我可能错过了什么

  • 我通过应用的论点:
/usr/bin/fwdd -l 0-3 -n 4 --vdev=net_tap0,iface=eth0
  • 设置大页面
function setup_hugepages()
{
    echo "Setup hugepages"
    sysctl -w vm.nr_hugepages=1024
    echo 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

    MOUNT_POINT="/mnt/huge"
    if [ ! $(mountpoint -q "${MOUNT_POINT}") ]; then
        echo "Mounting hugepages"
        mkdir -p ${MOUNT_POINT}
        mount -t hugetlbfs nodev ${MOUNT_POINT}
    else
        echo "Hugepages are already mounted at ${MOUNT_POINT}"
    fi
}
  • 创建容器
docker run -itd --privileged --cap-add=ALL \
    -v /sys/bus/pci/devices:/sys/bus/pci/devices \
    -v /sys/kernel/mm/hugepages:/sys/kernel/mm/hugepages \
    -v /sys/devices/system/node:/sys/devices/system/node \
    -v /dev:/dev \
    -v /mnt/huge:/mnt/huge \
    -v /sys/fs/cgroup:/sys/fs/cgroup:ro \
    --name nstk nstk_image
  • dpdk 应用程序的一部分
int main(int argc, char* argv[])
{
    int ret = rte_eal_init(argc, argv);
    if (ret < 0) {
        NSTK_LOG_DEBUG("Error: EAL initialization failed");
        return EXIT_FAILURE;
    }

    if (rte_eth_dev_count_avail() == 0) {
        NSTK_LOG_DEBUG("Error: No available Ethernet ports");
        return EXIT_FAILURE;
    }
...
c
  • 1 个回答
  • 71 Views
Martin Hope
theKMan747
Asked: 2025-04-27 22:22:09 +0800 CST

有没有办法确定某个类型是否未定义?

  • 7

我有一个Type_##type依赖于某个宏 type_create 的类型:

#define type_create(type) { \
    typedef struct { \
        type* ptr, \
    } Type_##type; \

我有一些依赖它的宏。现在我想知道我是否可以#ifndef针对某个类型执行类似操作,例如,

#ifndef Type_int
type_create(int);
#endif

除类型外。

c
  • 1 个回答
  • 50 Views
Martin Hope
mafesm
Asked: 2025-04-27 21:27:26 +0800 CST

使用 bison 构建语法树 ($ ref issue)

  • 7

我正在进行一个项目,需要构建一个完整的 C 语言编译器。我一直在寻找这方面的资料,但什么也没找到。

我有一段关于函数声明的语法规则:

fun_declaracao:
    tipo_especificador ID APR { 
        // Start of semantic action after parsing the return type (tipo_especificador), 
        // the function name (ID), and the opening parenthesis (APR).

        // Initialize function type as "erro" to detect issues later.
        char* tipo_fun = "erro";

        // Set the current function and scope to the function name.
        // These are likely used elsewhere to keep track of context during parsing.
        funcao_at = $2;
        escopo_at = $2;

        // Check if this function name is already declared in the global scope.
        if (busca(T, tm_tab, $2, "global") != -1) {
            // If found, report a semantic error: function already declared.
            erro_semantico("Funcao ja declarada", $2, yylineno);
        } else {
            // If not found, insert this new function into the symbol table.
            // Parameters: symbol table T, temporary table tm_tab,
            // function name $2, symbol kind "func", return type $1, line number, scope "global".
            add(&T, &tm_tab, $2, "func", $1, yylineno, "global");

            // Mark the identifier as valid for future reference.
            tipo_fun = "id"; 
        }
    } params FPR composto_declaracao {
        // This is the second semantic action, after the full function header and body have been parsed:
        // - params: the parameter list
        // - FPR: closing parenthesis
        // - composto_declaracao: the function body block

        // Build a syntax tree node representing the whole function declaration.
        // It includes 4 children: return type, function name, parameters, and body.
        $$ = novo("fun_declaracao", NULL, 4, 
                  novo($1, $1, 0),     // Return type node
                  novo($2, tipo_fun, 0), // Function name node with type info
                  $4,                 // Parameters node
                  $6);                // Function body node

        // After building the function, reset context to global (we're outside the function now).
        escopo_at = "global";
        funcao_at = NULL;
    }
;

因此,当我运行它时,出现以下错误:

bison -d parser.y
parser.y:124.86-87: $4 of `fun_declaracao' has no declared type
parser.y:124.90-91: $6 of `fun_declaracao' has no declared type
makefile:13: recipe for target 'parser.tab.c' failed
make: *** [parser.tab.c] Error 1

我认为这是一个愚蠢的问题,可能我只是不理解 bison 语法。

这是我的 %type 声明:

%union {
    char *string;
    NO *no;
    char *tipo; 
}

%token <string> ID
%token <string> NUM 

%token  INT VOID WHILE RETURN PEV VIR ERRO

%type <tipo> tipo_especificador

%type <no> expressao var simples_expressao soma_expressao termo fator 
%type <no> programa declaracao_lista declaracao var_declaracao fun_declaracao 
%type <no> params param_lista param composto_declaracao 
%type <no> local_declaracoes statement_lista statement expressao_declaracao selecao_declaracao iteracao_declaracao 
%type <no> retorno_declaracao args arg_lista relacional
c
  • 1 个回答
  • 37 Views
Martin Hope
devmauv
Asked: 2025-04-26 05:09:10 +0800 CST

使用 CryptSignMessage/电子令牌生成 PKCS7 签名

  • 6

我正在使用 CryptSignMessage 和 etoken(safenet)生成 p7s,但将其插入 PDF 后,Adobe 表示无法验证签名,因为文档已被修改或损坏。

这是我的 C 函数:

int GeneratePKCS7Signature(const BYTE * pbData, DWORD cbData,
  const CERTIFICATES_INFO * certInfo, BYTE ** ppbPkcs7, DWORD * pcbPkcs7) {
  if (!pbData || cbData == 0 || !certInfo || !certInfo -> signerCert || !ppbPkcs7 || !pcbPkcs7) {
    printf("Invalid parameters.\n");
    return 1;
  }
  printf("Start GeneratePKCS7Signature\n");
  // Verify that the signing certificate has its private key associated (using SafeNet etoken)
  NCRYPT_KEY_HANDLE hKey = 0;
  BOOL freeKey = FALSE;
  if (!CryptAcquireCertificatePrivateKey(certInfo -> signerCert,
      CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG,
      NULL,
      (HCRYPTPROV_OR_NCRYPT_KEY_HANDLE * ) & hKey,
      NULL, &
      freeKey)) {
    printf("Error searching for the private key of the signing certificate: %lu\n", GetLastError());
    return 1;
  }

  if (freeKey && hKey)
    NCryptFreeObject(hKey);

  // Build the array of certificates to be included in thePKCS#7:
  // The signing certificate is included, then the intermediate certificates and finally the root certificates
  size_t totalCertCount = 1 + certInfo -> numIntermediates + certInfo -> numRoots;
  PCCERT_CONTEXT * rgpCerts = (PCCERT_CONTEXT * ) malloc(totalCertCount * sizeof(PCCERT_CONTEXT));
  if (!rgpCerts) {
    printf("Error allocating memory for the certificate array.\n");
    return 1;
  }
  size_t idx = 0;
  rgpCerts[idx++] = certInfo -> signerCert;
  for (size_t i = 0; i < certInfo -> numIntermediates; i++) {
    rgpCerts[idx++] = certInfo -> intermediates[i];
  }
  for (size_t i = 0; i < certInfo -> numRoots; i++) {
    rgpCerts[idx++] = certInfo -> roots[i];
  }

  // Configure the structure CRYPT_SIGN_MESSAGE_PARA.

  CRYPT_SIGN_MESSAGE_PARA signPara;
  memset( & signPara, 0, sizeof(signPara));
  signPara.cbSize = sizeof(CRYPT_SIGN_MESSAGE_PARA);
  signPara.dwMsgEncodingType = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;
  signPara.pSigningCert = certInfo -> signerCert;
  signPara.HashAlgorithm.pszObjId = OID_RSA_SHA256; // SHA256
  signPara.cMsgCert = (DWORD) totalCertCount;
  signPara.rgpMsgCert = rgpCerts;
  signPara.cAuthAttr = 0;
  signPara.dwFlags = 0;
  signPara.dwInnerContentType = 0;

  // Prepare the parameters for the function CryptSignMessage.
  const BYTE * rgpbToBeSigned[1] = {
    pbData
  };
  DWORD rgcbToBeSigned[1] = {
    cbData
  };

  // First call to get the required size of the PKCS#7.
  DWORD cbPkcs7 = 0;
  if (!CryptSignMessage( & signPara,
      TRUE, // Sign detached
      1,
      rgpbToBeSigned,
      rgcbToBeSigned,
      NULL, &
      cbPkcs7)) {
    printf("Error calculating the size of the PKCS#7: 0x%x\n", GetLastError());
    free(rgpCerts);
    return 1;
  }

  BYTE * pbPkcs7 = (BYTE * ) HeapAlloc(GetProcessHeap(), 0, cbPkcs7);
  if (!pbPkcs7) {
    printf("Error allocating memory for the PKCS#7.\n");
    free(rgpCerts);
    return 1;
  }

  // Second call to generate the PKCS#7.
  if (!CryptSignMessage( & signPara,
      TRUE, // Sign detached
      1,
      rgpbToBeSigned,
      rgcbToBeSigned,
      pbPkcs7, &
      cbPkcs7)) {
    printf("Error generating the PKCS#7: 0x%x\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, pbPkcs7);
    free(rgpCerts);
    return 1;
  }

  * ppbPkcs7 = pbPkcs7;
  * pcbPkcs7 = cbPkcs7;

  free(rgpCerts);
  return 0;
}

生成的 p7s 是:firma.p7s 测试 pdf 签名:pdf

我尝试了几个不同的 PDF 文件,并在签名前后验证了 SHA256 哈希值。我还使用 QPDF 等不同工具分析了 PDF 结构。因此,我认为问题出在 PKCS7、某些属性或签名本身,导致 Adob​​e 无法验证。我还使用 ANS.1 解码器进行了检查,尽管我修正了一些问题,但错误仍然存​​在。

c
  • 1 个回答
  • 50 Views
Martin Hope
Jackoo
Asked: 2025-04-25 17:21:15 +0800 CST

为什么在外部内联函数中调用静态内联函数会出现问题?

  • 8
// lib.h
#pragma once
static inline int static_inline(int x) { return x; }
inline int extern_inline(int x) { return static_inline(x); }
// lib.c
#include "lib.h"
extern inline int extern_inline(int x);
// app.c
#include "lib.h"

编译 app.c 时,gcc 给出以下警告:

'static_inline' 是静态的,但用于非静态的内联函数 'extern_inline'。

为什么这是个问题?我的解释是:在 app.c 中,如果extern_inline 不是内联的,那么它就变成了一个函数调用,其实现细节(调用static_inline)可以忽略。如果extern_inline 是内联的,那么它就有完整的定义,其他翻译单元中的定义也可以忽略。

c
  • 1 个回答
  • 75 Views
Martin Hope
Newton's in-law
Asked: 2025-04-25 15:08:32 +0800 CST

标准 C 文件是否编译?

  • 10

每当我们创建一个包含自定义函数定义的文件,例如,以及包含函数声明的utils.c相应头文件时,我必须使用类似 的命令将该文件与我正在使用的驱动程序代码一起编译。utils.hutils.cgcc driver.c utils.c -o my_exe

那么什么指令可以编译我们包含其头文件的标准 C 文件stdio.h?

c
  • 5 个回答
  • 156 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve