Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
BAD_ACCESS_ERR in a simple string copy function in c

I'm implementing a basic string copy function in c like so:

void copy(char* src, char* dst) {
    while (*src) {
        *dst = *src;
        dst++, src++;
    }
}

I call it like so:

int main(int argc, char* argv[]) {
    char* src = "Hello World!";
    char* dst = "AAAAAAAAAAAA";

    printf("Source: %s | Des: %s\n", src, dst);
    copy(src, dst);
    printf("Source: %s | Des: %s", src, dst);
}

When debugging with lldb, I know for a fact that src and dst in copy are valid pointers. And yet, when *dst = *src executes, my program gets thrown a BAD_ACCESS_ERR. How is this even possible? The compiler should be statically allocating the memory for src and dst. Both are of equal sizes in terms of string lengths. The error doesn't even get thrown on the null-terminating character, it gets thrown on the first time the assign statement executes. What am I not seeing? Is this macOS specific?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

char* dst = "AAAAAAAAAAAA";

You define destination to point to a section of memory that could be read only -- string literals are allowed by the C standard to be kept into a read only segment. 6.4.5p6 String literals:

  1. ... If the program attempts to modify such an array, the behavior is undefined.

You need to define the destination in heap or into a vector, that you are sure to allocate correctly.

dst = malloc(SIZE);

or

char dst[100];

In the first case make sure you call free, in the second case make sure you do not access it after its scope or the source does not have more than 99 characters+NUL.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda