Jump to content
Ganav

Programare

Recommended Posts

Posted

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.

Posted

#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.

Posted

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)).

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...