Program signal: "EXC_BAD_ACCESS"?

I am making a command line program in C using Xcode. When you run the program, it initially does what it should do (asks me for the path to the file). However, when I enter a valid and existing file path, it causes the following error:

Program received signal:  "EXC_BAD_ACCESS". sharedlibrary apply-load-rules all (gdb)

I have two warnings in my program, each of which is associated with the strcat function. Warnings:

warning: implicit declaration of function 'strcat'

and

warning: incompatible implicit declaration of built-in function 'strcat'

I am wondering why my program is not executing properly.

Thanks Mike

My code is published below:

#include "stdlib.h"
int main (void)
{
   char *string1;
   printf("Type in your file path: ");
   scanf("%s", string1);
   char *string2 = "tar czvf YourNewFile.tar.gz ";
   strcat(string2, string1);
   system(string2);
}

Maybe this is due to the distribution of characters?

+3
source share
2 answers

Examine this line:

char *string1

and this line:

scanf("%s", string1);

1, , , :

char string1[100]

100 - .

.

, , #include "string.h" , #include.

+5

string1, scanf , . , string2 , string1 , strcat , char string2[] = "tar czvf YourNewFile.tar.gz ";.

​​ -, , :

#include <stdio.h>  /* printf, sprintf, fgets */
#include <string.h> /* strcat, strlen */
#include <stdlib.h> /* malloc */

#define TAR "tar czvf YourNewFile.tar.gz"

int main(void) {
    char path[100] = { 0 };  /* Initialize to all 0 bytes.           */
    char *cmd;               /* We'll allocate space for this later. */
    int   len;

    printf("Type in your file path: ");
    fgets(path, sizeof(path), stdin);   /* Read at most 100 characters into path */

    /*
     * Remove the trailing newline (if present).
     */
    len = strlen(path);
    if(path[len - 1] == '\n')
        path[len - 1] = '\0';

    /*
     * Allocate room for our command. 
     */
    cmd = malloc(
          strlen(TAR)   /* Room for the base tar command.         */
        + 1             /* One more for the space.                */
        + strlen(path)  /* Room for the path we read.             */
        + 1             /* One more for the final nul terminator. */
    );

    /*
     * You could also use a bunch of strcpy and strcat stuff for
     * this but sprintf is less noisy and safe as long as you've
     * properly allocated your memory.
     */
    sprintf(cmd, "%s %s", TAR, path);

    /*
     * This is vulnerable to unpleasant things in `path` (such as spaces,
     * &, >, <, ...) but this will do as a learning exercise. In real life
     * you'd probably want to use fork and exec for this to avoid the  
     * interface issues with the shell.
     */
    system(cmd);  

    /*
     * Free the memory we allocated.
     */
    free(cmd);

    /*
     * You need a return value because of "int main(...)". Zero is
     * the standard "all well" return value.
     */
    return 0;
}

-, , , - .

.

+6

All Articles