Ganav Posted June 21, 2014 Report Posted June 21, 2014 Avem urmatorul program:#include <stdio.h>#include <string.h>void customAlloc(char* str, size_t size) { if((str = (char*)malloc(size * sizeof(char))) == NULL) { perror("Nu putem aloca memorie. Cauza este:"); exit(1); }}int main(int argc, char** argv) { char* str = (char*)0; customAlloc(str, 4); strcpy(str, "RST"); printf("%s:\n", str); free(str); str = (void*)0; return 0;}Presupunem ca lucram pe Linux. Compilam aplicatia si la rulare vedem ca avem un segmentation fault la apelul functiei strcpy(). Ce se intampla si cum putem modifica functia customAlloc() pentru a aloca in mod corespunzator memorie. Quote
lutulik Posted June 22, 2014 Report Posted June 22, 2014 #include <stdio.h>#include <string.h>#include <stdlib.h> /* nu stiu cum iti merge pe linux fara asta, pentru ca "malloc" si "free" sunt definite in biblioteca asta */void customAlloc(char **str, int size) { //daca vrei sa transmiti ceva care se schimba intr-o functie *str = (char*)malloc(size * sizeof(char)); if(!str) { perror("Nu putem aloca memorie. Cauza este:"); exit(1); }}int main(int argc, char** argv) { char *str; //nu e nevoie sa il setezi pe NULL, oricum "strcpy" ii schimba valoarea. customAlloc(&str, 4); strcpy(str, "RST"); printf("%s:\n", str); free(str); str = (void*)0; return 0;}In C, everything is passed by value. A general rule to remember is, you can't change the value of a parameter passed to a function. If you want to pass something that needs to change, you need to pass a pointer to it. Quote
Ganav Posted June 22, 2014 Author Report Posted June 22, 2014 Bravo. Valorile le-am pus pe NULL deoarece imi dadeau warning-uri(este bine pentru portabilitate ca fiecare variabila sa fie initializata inainte de a fi utilizata(pot exista diferente subtile intre compilatoare)). Quote