strcpy / warning



  • Hallo, ich brauch eure Hilfe. Bei Ausführung des folgenden Codestücks bekomm ich eine Warnung in der Funktion "really_bad_copy_function".

    Warning: function returns adress of local variable

    Wie bekomm ich das hin, das es ohne diese Warnmeldung kompiliert?

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define MAGIC_CONSTANTS_ARE_BAD 1024
    
    /* 
     * Diese Funktion soll eine Kopie von string_to_copy machen.
     * Wird schon klappen, oder?
     */
    
    char* really_bad_copy_function(char *string_to_copy) {
    
    	char return_string[MAGIC_CONSTANTS_ARE_BAD];
    	strncpy(return_string, string_to_copy, MAGIC_CONSTANTS_ARE_BAD - 1);
    	return return_string; 
    }
    
    int main () {
    
    	char *a = "Hello World\n", *b;
    
    	char *c;
    
        b = malloc (strlen(a)+1);
    
        strcpy(b, a);
    
    	c = really_bad_copy_function(a);
    
    	printf("%s", b);
    
    	printf("%s", c);
    
        free(b);
    
    	return 0;
    }
    


  • Muss es dafür extra ein neuer Thread sein?
    Nein, muss es nicht.

    Das ganze Programm sieht nach einem Beispiel dafür aus, genau dieses Problem aufzuzeigen.

    Die Funktion heißt ja nicht umsonst really bad.

    Nutze in Zukunft malloc , so wie es bei b gezeigt wird.
    Oder ein anderes (ausreichend großes) Array.


Anmelden zum Antworten